Excelling in excel with java

import java.io.File;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

public class WriteDataToExcel {

    public static void main(String[] args) throws Exception

    {

        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet spreadsheet

            = workbook.createSheet(" Student Data ");

        XSSFRow row;

        Map<String, Object[]> studentData

            = new TreeMap<String, Object[]>();

        studentData.put(

            "1",

            new Object[] { "Roll No", "NAME", "Year" });

        studentData.put("2", new Object[] { "128", "Aditya",

                                            "2nd year" });

        studentData.put(

            "3",

            new Object[] { "129", "Narayana", "2nd year" });

        studentData.put("4", new Object[] { "130", "Mohan",

                                            "2nd year" });

        studentData.put("5", new Object[] { "131", "Radha",

                                            "2nd year" });

        studentData.put("6", new Object[] { "132", "Gopal",

                                            "2nd year" });

        Set<String> keyid = studentData.keySet();

        int rowid = 0;

        for (String key : keyid) {

            row = spreadsheet.createRow(rowid++);

            Object[] objectArr = studentData.get(key);

            int cellid = 0;

            for (Object obj : objectArr) {

                Cell cell = row.createCell(cellid++);

                cell.setCellValue((String)obj);

            }

        }

        FileOutputStream out = new FileOutputStream(

            new File("C:/savedexcel/GFGsheet.xlsx"));

        workbook.write(out);

        out.close();

    }

}

Рассказывает автор блога javarevisited.blogspot.ru


Из этой статьи вы сможете узнать о записи и чтении данных из Excel файлов в Java (будет рассмотрен как XLS, так и XLSX формат). Мы будем использовать библиотеку Apache POI и сосредоточимся на работе с типами String и Date, работа с последним происходит достаточно хитро. Напомню, что работу с числами мы уже рассмотрели в другой статье.

Библиотеку poi-XX.jar вы можете использовать для всех старых (xls, doc, ppt) файлов Microsoft Office, для новых (xlsx, docx, pptx) вам понадобится poi-ooxml-XX.jar. Очень важно понимать, что к чему относится, т.к. используемые классы тоже разные — для старых расширений это HSSFWorkbook, а для новых — XSSFWorkbook.

Подготовка: загрузка библиотек и зависимостей

Конечно, существует достаточно много открытых библиотек, которые позволяют работать с Excel файлами в Java, например, JXL, но мы будем использовать имеющую самый обширный API и самую популярную — Apache POI. Чтобы её использовать, вам нужно скачать jar файлы и добавить их через Eclipse вручную, или вы можете предоставить это Maven.

Во втором случае вам нужно просто добавить следующие две зависимости:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>
  </dependencies>

Самое удобное в Maven — что он загрузит не только указанные poi.jar и poi-ooxml.jar, но и все jar файлы, которые используются внутри, то есть xmlbeans-2.6.0.jar, stax-api-1.0.1.jar, poi-ooxml-schemas-3.12.jar и commons-codec-1.9.jar.

Если вы будете добавлять библиотеки вручную — не забудьте о вышеназванных файлах. Скачать всё можно отсюда. Помните — если вы загрузите только poi-XX.jar, то ваш код скомпилируется без ошибок, но потом упадёт с java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject, так как внутри будет вызываться xmlbeans.jar.

Запись

В этом примере мы запишем в xls файл следующие данные: в первую ячейку — строку с именем, а во вторую — дату рождения. Вот пошаговая инструкция:

  • Создаём объект HSSFWorkBook;
  • Создаём лист, используя на объекте, созданном в предыдущем шаге, createSheet();
  • Создаём на листе строку, используя createRow();
  • Создаём в строке ячейку — createCell();
  • Задаём значение ячейки через setCellValue();
  • Записываем workbook в File через FileOutputStream;
  • Закрываем workbook, вызывая close().

Для записи строк или чисел этого вполне достаточно, но чтобы записать дату, нам понадобится сделать ещё кое-что:

  • Создать DateFormat;
  • Создать CellStyle;
  • Записать DateFormat в CellStyle;
  • Записать CellStyle в ячейку;
  • Теперь в эту ячейку можно записать объект Date через всё тот же setCellValue;
  • Чтобы дата поместилась в ячейку, нам нужно добавить столбцу свойство автоматически менять размер: sheet.autoSizeColumn(1).

Всё вместе это будет выглядеть так:

@SuppressWarnings("deprecation")
    public static void writeIntoExcel(String file) throws FileNotFoundException, IOException{
        Workbook book = new HSSFWorkbook();
        Sheet sheet = book.createSheet("Birthdays");

        // Нумерация начинается с нуля
        Row row = sheet.createRow(0); 
        
        // Мы запишем имя и дату в два столбца
        // имя будет String, а дата рождения --- Date,
        // формата dd.mm.yyyy
        Cell name = row.createCell(0);
        name.setCellValue("John");
        
        Cell birthdate = row.createCell(1);
        
        DataFormat format = book.createDataFormat();
        CellStyle dateStyle = book.createCellStyle();
        dateStyle.setDataFormat(format.getFormat("dd.mm.yyyy"));
        birthdate.setCellStyle(dateStyle);
        
 
        // Нумерация лет начинается с 1900-го
        birthdate.setCellValue(new Date(110, 10, 10));
        
        // Меняем размер столбца
        sheet.autoSizeColumn(1);
        
        // Записываем всё в файл
        book.write(new FileOutputStream(file));
        book.close();
    }

Чтение

Теперь мы считаем из только что созданного файла то, что мы туда записали.

  • Для начала создадим HSSFWorkBook, передав в конструктор FileInputStream;
  • Получаем лист, передавая в getSheet() его номер или название;
  • Получаем строку, используя getRow();
  • Получаем ячейку, используя getCell();
  • Узнаём тип ячейки, используя на ней getCellType();
  • В зависимости от типа ячейки, читаем её значения, используя getStringCellValue(), getNumericCellValue() или getDateCellValue();
  • Закрываем workbook используя close().

Напомню, что дату Excel хранит как числа, т.е. тип ячейки всё равно будет CELL_TYPE_NUMERIC.

В виде кода это будет выглядеть следующим образом:

public static void readFromExcel(String file) throws IOException{
        HSSFWorkbook myExcelBook = new HSSFWorkbook(new FileInputStream(file));
        HSSFSheet myExcelSheet = myExcelBook.getSheet("Birthdays");
        HSSFRow row = myExcelSheet.getRow(0);
        
        if(row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_STRING){
            String name = row.getCell(0).getStringCellValue();
            System.out.println("name : " + name);
        }
        
        if(row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
            Date birthdate = row.getCell(1).getDateCellValue();
            System.out.println("birthdate :" + birthdate);
        }
        
        myExcelBook.close();
        
    }

В заключение

Как уже упомналось выше, чтение из xlsx файлов ничем принципиально не отличается — нужно только вместо HSSFWorkBook, HSSFSheet, HSSFRow (и прочих) из poi-XX.jar использовать XSSFWorkBook, XSSFSheet, XSSFRow из poi-ooxml-XX.jar. Это всё, что вам нужно знать для чтения и записи в файлы Excel. Разумеется, с помощью библиотеки Apache POI вы можете сделать гораздо больше, но эта статья должна помочь вам быстрее в ней освоиться.

Перевод статьи «How to Read Write Excel file in Java — POI Example»

Интеграция электронных таблиц MS Excel и Java.

Описание:

В современном мире очень много случаев, при которых необходимо интегрировать MS
Excel с Java. Например, при разработке Enterprise-приложения в некой финансовой
сфере, вам необходимо предоставить счет для заинтересованных лиц, а проще всего
выставлять счет на MS Excel.

Обзор существующих API MS Excel для Java:

Рассмотрим основные API:

  • Docx4j — это API с открытым исходным кодом, для создания и манипулирования документами формата Microsoft Open XML, к которым отросятся Word docx, Powerpoint pptx, Excel xlsx файлы. Он очень похож на Microsoft OpenXML SDK, но реализован на языке Java. Docx4j использует JAXB архитектуру для создания представления объекта в памяти. Docx4j акцентирует свое внимание на всесторонней поддержке заявленного формата, но от пользователя данного API требуется знание и понимание технологии JAXB и структуры Open XML.

  • Apache POI — это набор API с открытым исходным кодом, который предлагает определенные функции для чтения и записи различных документов, базирующихся на Office Open XML стандартах (OOXML) и Microsoft OLE2 форматe документов (OLE2). OLE2 файлы включают большинство Microsoft Office форматов, таких как doc, xls, ppt. Office Open XML формат это новый стандарт базирующийся на XML разметке, и используется в файлах Microsoft office 2007 и старше.

  • Aspose for Java — набор платных Java APIs, которые помогают разработчикам в работе с популярными форматами бизнес файлов, такими как документы Microsoft Word, таблицы Microsoft Excel, презентации Microsoft PowerPoint, PDF файлы Adobe Acrobat, emails, изображения, штрих-коды и оптические распознавания символов.

Каждое API проектируется для того, чтобы выполнять широкий спектр создания документов, различные манипуляции и преобразования быстро и легко, экономя время и позволяя разработчикам успешно программировать. Ни один API с открытым исходным кодом не имеет одной и той же комплексной поддержки функций.

Все Aspose’s APIs используют простую объектную модель документа, а одно API предназначено для работы с набором связанных форматов. Aspose’s Microsoft Office APIs, Aspose.Cells, Aspose.Words, Aspose.Slides, Aspose.Email, и Aspose.Tasks легки в работе, эффективны, надежны и независимы от других библиотек.

Преимуществом APIs с открытым исходным кодом является то, что они бесплатны и каждый может настроить их под свои задачи и цели. Это очень удобно, если у пользователя есть достаточно времени и ресурсов. Однако данные APIs не всегда имеют поддержку или документацию, и поддерживают небольшое количество функций и вариантов. Этот недостаток стоит разработчикам времени, и сокращает надежность их приложений. К преимуществам проприетарных (коммерческих) API можно отнести комплексную поддержку функционала с подробной документацией, регулярное обновление, гарантию отсутствия ошибок и обратную связь с разработчиками APIs.

В данной программе будем использовать Apache POI

Ссылки на полезные ресурсы

  • https://habr.com/post/56817/
  • https://poi.apache.org/apidocs/index.html — официальная документация
  • http://java-online.ru/java-excel.xhtml

Задание:

В данной работе вы должны реализовать следующее:

  1. Чтение с ячейки MS Excel в Java

  2. Запись с Java в MS Excel

Инструкция

  • Для обращения к MS Excel версии до 2003 включительно года с Java используется класс HSSFWorkbook
  • Для обращения к MS Excel версии 2007 и позднее с Java используется класс XSSFWorkbook
  • При операциях Обновление или Запись необходимо, чтобы MS Excel был закрыт.
Чтение ячейки с MS Excel

Чтобы считать данные с xlsx необходимо исполнить следующие шаги:

    //filePath - это путь до MS Excel
    Workbook book = new XSSFWorkbook(new FileInputStream(filePath);
    //считывается лист по индексу sheet_index. sheet_index начинается с 0
    Sheet sheet = book.getSheetAt(sheet_index);
    //считывается row по индексу row_index. row_index начинается с 0
    Row row = sheet.getRow(row_index);
    //считывается cell по индексу cell_index. cell_index начинается с 0
    Cell cell = sheet.getCell(cell_index);
Запись в ячейку MS Excel
    Workbook book = new XSSFWorkbook();
    //name - имя листа
    Sheet sheet = book.createSheet(name);
    Row row = sheet.createRow(i);
    Cell cell = row.createCell(j);
    FileInputStream fileOut = new FileInputStream(filePath);
    book.write(fileOut);
    fileOut.close();
Обновление ячейки в существующем листе MS Excel
    Workbook workbook = new XSSFWorkbook(new FileInputStream(filePath));
    Sheet sheet = workbook.getSheetAt(i);
    Row row = sheet.getRow(j);
    Cell cell = row.getCell(k);
    cell.setCellValue(value);

Подготовка: загрузка библиотек и зависимостей

Конечно, существует достаточно много открытых библиотек, которые позволяют работать с Excel файлами в Java, например, JXL, но мы будем использовать имеющую самый обширный API и самую популярную — Apache POI. Чтобы её использовать, вам нужно скачать jar файлы и добавить их через Eclipse вручную, или вы можете предоставить это Maven.

Во втором случае вам нужно просто добавить следующие две зависимости:

	<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>
  </dependencies>

Самое удобное в Maven — что он загрузит не только указанные poi.jar и poi-ooxml.jar, но и все jar файлы, которые используются внутри, то есть xmlbeans-2.6.0.jar,
stax-api-1.0.1.jar, poi-ooxml-schemas-3.12.jar и commons-codec-1.9.jar

Выполнение:

  1. Создать проект на java с помощью maven.

  2. Следовать инструкции «Подготовка:…» описанная выше.

  3. Создать Excel файл в корневой папке проекта.

  4. Записать в A1 и A2 любые целые числа.

  5. В папке src/main/java создать класс IOCell

    1. Создать поле
    1. Создать конструктор
    IOCell(String filePath) { this.filePath = new File(filePath)}
    1. Создать метод для чтения c Excel в Java
    public Cell getCell(int sheet, int row, int column) {
        Workbook workbook = null;
        try (FileInputStream file = new FileInputStream(filePath)) {
            workbook = new XSSFWorkbook(file);
        } catch (FileNotFoundException e) {
            System.out.println("file is not exists");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook.getSheetAt(sheet).getRow(row).getCell(column);
    }
    1. Создать метод для записи с Java в Excel
        public void setCell(int row, int column, double val) {
        Workbook workbook = null;
         try (FileInputStream file = new FileInputStream(filePath)) {
             workbook = new XSSFWorkbook(file);
             Sheet sheet = workbook.getSheetAt(0);
             sheet.getRow(row).getCell(column).setCellValue(val);
         } catch (IOException e) {
             e.printStackTrace();
         }
        try (OutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        } catch (FileNotFoundException e) {
            System.out.println("file is not exist AAAA");
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    
  6. В папке src/main/java создать класс Main

    1. Создать поле
        private static final String filePath = "NAME_OF_EXCEL_FILE";
    1. Создать метод
    public static void main(String[] args) {
        IOCell ioCell = new IOCell(filePath);
    
        Cell x = ioCell.getCell(0, 1, 0);
        Cell y = ioCell.getCell(0,  1, 1);
        System.out.println("first number: " + x.toString());
        System.out.println("second number: " + y.toString());
        //Write x * y
        ioCell.setCell(4, 0, x.getNumericCellValue() * y.getNumericCellValue());
        //Write x + y
        ioCell.setCell(4, 1, x.getNumericCellValue() + y.getNumericCellValue());
        System.out.println("Interactions is complete successfully");
    }
  7. Запускаем приложение и смотрим в консоль.

Learn how to use the Jakarta POI

Whether you have balance sheets, account information downloads, tax calculations, or pay slips, they all tend to come in Microsoft Excel. Non-IT professionals feel comfortable using Microsoft Excel as a data exchange technology. The Jakarta POI (Poor Obfuscation Implementation) API is a fantastic way for Java programmers to access Microsoft document formats. The most mature API from Jakarta POI is the HSSF (Horrible Spreadsheet Format) API, which accesses Microsoft Excel documents.

In this article, I walk you through the steps for creating and reading Excel documents, and for using fonts and cell styling—all using Java.

Note: You can download the source code for all the examples in this article from Resources.

POI terminology

The key terms associated with Jakarta POI are as follows:

  • POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats
  • HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel
  • HDF (Horrible Document Format): Java API to read and write Microsoft Word 97
  • HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java

Create an Excel document

The Jakarta POI API can be used to create an Excel document programmatically. The important steps involved are:

  • Create a workbook: HSSFWorkbook workbook = new HSSFWorkbook();
  • Create a new worksheet in the workbook and name the worksheet «Java Excels»: HSSFSheet sheet = workbook.createSheet("Java Excels");
  • Create a new row in the sheet: HSSFRow row = sheet.createRow((short)0);
  • Create a cell in the row: HSSFCell cell = row.createCell((short) 0);
  • Put some content in the cell: cell.setCellValue("Have a Cup of XL");
  • Write the workbook into the filesystem: workbook.write(fileOutputStream);

Read data from the Excel document

In this example, you’ll see how to read values from an Excel document.

Let’s assume this is our Excel sheet:

Employee Name Specialization Designation
Anbu Programming Senior Programmer
Jason Banking Industry Business Analyst
Ramesh Databases DBA
MackyB Accounting Delivery Head

The key steps in reading the Excel sheet are as follows:

  • Create a new Excel document reference: HSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));.
  • Refer to the sheet: By default, the first sheet in the Excel document is at reference 0: HSSFSheet sheet = workbook.getSheetAt(0);. A sheet can also be referred to by name. Let’s assume that the Excel sheet has the default name «Sheet1». It can be referred to as follows: HSSFSheet sheet = workbook.getSheet("Sheet1");.
  • Refer to a row: HSSFRow row = sheet.getRow(0);.
  • Refer to a cell in the row: HSSFCell cell = row.getCell((short)0);.
  • Get the values in that cell: cell.getStringCellValue();.

A practical example

Now let’s assume that we want to see the list of all declared methods and member variables in a jar file. It would be ideal to have a consolidated list of all information in one single file. We would like to view the information so that the class names are in the first column, declared fields in the second column, and declared methods in the third column, with the column headings appearing in red.

The program will have to complete the following activities:

  • Unzip the jar file
  • Read all classfiles in the jar file
  • Load the classes in the jar file
  • Using reflection, get the declared methods and fields
  • Write the class information into an Excel sheet using Jakarta POI

Let’s concentrate on just the interesting steps of Jakarta POI usage:

  • Create a new Excel document: workbook = new HSSFWorkbook();
  • Make a worksheet in that document and give the worksheet a name: sheet = workbook.createSheet("Java Class Info");
  • Set the first three columns’ widths: sheet.setColumnWidth((short)0,(short)10000 );
  • Create the header line: HSSFRow row = sheet.createRow((short)0);
  • Create and set font and cell style:
       HSSFFont font = workbook.createFont();
       font.setColor(HSSFFont.COLOR_RED);
       font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
       // Create the style
          HSSFCellStyle cellStyle= workbook.createCellStyle();
          cellStyle.setFont(font);
    
  • Use the cell style:
          HSSFCell cell = row.createCell((short) 0);
          cell.setCellStyle(cellStyle);
          cell.setCellType(HSSFCell.CELL_TYPE_STRING);
          cell.setCellValue("Class Name ");
    
  • Write the output file:
          FileOutputStream fOut = new FileOutputStream(outputFile);
          // Write the Excel sheet
          workbook.write(fOut);
          fOut.flush();
          // Done deal. Close it.
          fOut.close();
    

Summary

As demonstrated in this article, Java developers no longer need to wince at data in Excel sheets. We can programmatically access Excel documents. Have a cup of Java, and excel in Excel!

Elango
Sundaram is an experienced Java programmer with research
interests in distributed computing architecture, agent-based
technology and object-oriented methodology. He holds a master’s
degree in computer science from Virginia Tech University and has
written Distributed
computing using Jini and Websphere
Studio Application Developer Tail Plug-in (for WSAD 4.0).

This story, «Excelling in Excel with Java» was originally published by

JavaWorld.

Copyright © 2004 IDG Communications, Inc.

Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc. The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered. In this tutorial we will use Apache POI library to perform different functions on Microsoft Excel spreadsheet. Let’s get started. 

Tools & Technologies:

  1. Java JDK 1.5 or above
  2. Apache POI library v3.8 or above (download)
  3. Eclipse 3.2 above (optional)

1. Add Apache POI dependency

Make sure to include apache poi jar file to your project. If your project uses Maven as dependency management, add following in your Pom.xml file.

<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.8</version> </dependency>

Code language: HTML, XML (xml)

If you are not using Maven then you can directly add required JAR files in your classpath.

  1. Download poi-2.5.1.jar(or in this case 3.8) jar file.
  2. Include this file in your projects class path.
  3. Create new java project in eclipse with auto generated main function.

2. Read Excel File

To read an excel file, Apache POI provides certain easy-to-use APIs. In below sample code we use different classes from POI library to read content of cell from excel file. This is for quick reference.

import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; //.. FileInputStream file = new FileInputStream(new File("C:\test.xls")); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); //Get iterator to all cells of current row Iterator<Cell> cellIterator = row.cellIterator();

Code language: Java (java)

Notice how each class in POI library starts with HSSF prefix! e.g. HSSFWorkbook, HSSFSheet etc. HSSF stands for Horrible SpreadSheet Format! I’m not kidding.. It really is. Similar to HSSF, POI has different prefix for other file formats too:

  1. HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
  2. XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
  3. HPSF (Horrible Property Set Format) – reads “Document Summary” information from Microsoft Office files.
  4. HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
  5. HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
  6. HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
  7. HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
  8. HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files
  9. DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.

Working with .xlsx files

The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with newer xls format viz .xlsx, you need to see newer POI classes like:

import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet; //.. FileInputStream file = new FileInputStream(new File("C:\test.xlsx")); //Get the workbook instance for XLS file XSSFWorkbook workbook = new XSSFWorkbook (file); //Get first sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); //Get iterator to all cells of current row Iterator<Cell> cellIterator = row.cellIterator();

Code language: Java (java)

Use XSSFWorkbook and XSSFSheet class in all of the below examples in order to make them work with .xlsx files. Consider a sample excel file: test.xls

java read excel file

We will read above xls file using Apache POI and prints the data.

try { FileInputStream file = new FileInputStream(new File("C:\test.xls")); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows from first sheet Iterator < Row > rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //For each row, iterate through each columns Iterator < Cell > cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue() + "tt"); break; case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "tt"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "tt"); break; } } System.out.println(""); } file.close(); FileOutputStream out = new FileOutputStream(new File("C:\test.xls")); workbook.write(out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Code language: Java (java)

The above code is self explanatory. It read the sheet from workbook and iterate through each row and cell to print its values. Just note how we use different methods like getBooleanCellValuegetNumericCellValue etc to read cell value. Before reading a cell content, we need to first determine its type using method cell.getCellType() and then call appropriate method to read content. Output:

Emp Id Name Salary 1.0 John 2000000.0 2.0 Dean 420000.0 3.0 Sam 280000.0 4.0 Cass 6000000.0

Code language: CSS (css)

3. Create New Excel File

Let us create a new excel file and write data in it. Following is the API which we will use for this purpose.

import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; //.. HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet"); //Create a new row in current sheet Row row = sheet.createRow(0); //Create a new cell in current row Cell cell = row.createCell(0); //Set value to new value cell.setCellValue("Blahblah");

Code language: Java (java)

Below is the complete code that writes a new excel with dummy data:

HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet"); Map < String, Object[] > data = new HashMap < String, Object[] > (); data.put("1", new Object[] { "Emp No.", "Name", "Salary" }); data.put("2", new Object[] { 1 d, "John", 1500000 d }); data.put("3", new Object[] { 2 d, "Sam", 800000 d }); data.put("4", new Object[] { 3 d, "Dean", 700000 d }); Set < String > keyset = data.keySet(); int rownum = 0; for (String key: keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj: objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof Date) cell.setCellValue((Date) obj); else if (obj instanceof Boolean) cell.setCellValue((Boolean) obj); else if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Double) cell.setCellValue((Double) obj); } } try { FileOutputStream out = new FileOutputStream(new File("C:\new.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Code language: Java (java)

Output:

new.xls

java-write-excel file

4. Update Existing Excel File

Updating an existing excel file is straight forward. Open the excel using different API that we discussed above and set the cell’s value. One thing we need to note here is that we can update the excel file only when we close it first. 

update.xls

java-update-excel-before

Following Java code read the above excel file and doubles the salary of each employee:

try { FileInputStream file = new FileInputStream(new File("C:\update.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); Cell cell = null; //Update the value of cell cell = sheet.getRow(1).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); cell = sheet.getRow(2).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); cell = sheet.getRow(3).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); file.close(); FileOutputStream outFile = new FileOutputStream(new File("C:\update.xls")); workbook.write(outFile); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Code language: Java (java)

Steps to update excel file will be:

  1. Open excel file in input mode (inputstream)
  2. Use POI API and read the excel content
  3. Update cell’s value using different setCellValue methods.
  4. Close the excel input file (inputstream)
  5. Open same excel file in output mode (outputstream)
  6. Write content of updated workbook in output file
  7. Close output excel file

Output:

update.xls

java-update-excel-after

5. Adding Formulas

Apache POI provides API to add excel formulas to cell programmatically. Following method that comes handy for this:

cell.setCellFormula("someformula")

Code language: Java (java)

For example:

cell.setCellFormula("A2*B2*C5") //or cell.setCellFormula("SUM(A1:A7)")

Code language: Java (java)

Note: Formula string should not start with equal sign (=) Thus, following is incorrect way of adding formula:

cell.setCellFormula("=A2*B2*C5") //Ops! Won't work

Code language: Java (java)

The above code will throw:

org.apache.poi.ss.formula.FormulaParseException: The specified formula '=A2*B2*C5' starts with an equals sign which is not allowed.

Code language: JavaScript (javascript)

Following Java code creates a new excel sheet which calculates Simple Interest. It defines Principal amount, Rate of Interest and Tenure. We add an excel formula to calculate interest.

HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Calculate Simple Interest"); Row header = sheet.createRow(0); header.createCell(0).setCellValue("Pricipal Amount (P)"); header.createCell(1).setCellValue("Rate of Interest (r)"); header.createCell(2).setCellValue("Tenure (t)"); header.createCell(3).setCellValue("Interest (P r t)"); Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue(14500 d); dataRow.createCell(1).setCellValue(9.25); dataRow.createCell(2).setCellValue(3 d); dataRow.createCell(3).setCellFormula("A2*B2*C2"); try { FileOutputStream out = new FileOutputStream(new File("C:\formula.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Code language: Java (java)

Output:

formula.xls

java-excel-add-formula

Triggering Existing Excel Formulas

In certain cases your excel file might have formula defined and you may want to trigger those formulas since you updated it using POI. Following code snippet will do the trick.

FileInputStream fis = new FileInputStream("/somepath/test.xls"); Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("C:\test.xls") FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { Sheet sheet = wb.getSheetAt(sheetNum); for (Row r: sheet) { for (Cell c: r) { if (c.getCellType() == Cell.CELL_TYPE_FORMULA) { evaluator.evaluateFormulaCell(c); } } } }

Code language: Java (java)

We use FormulaEvaluator class to evaluate formula defined in each of the cell.

6. Adding Styles to Cell

Adding style to a cell is also piece of cake. Check following example which creates two new cell one with bold font and another with italic and add text to it.

HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Style example"); HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); HSSFCellStyle style = workbook.createCellStyle(); style.setFont(font); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("This is bold"); cell.setCellStyle(style); font = workbook.createFont(); font.setItalic(true); style = workbook.createCellStyle(); style.setFont(font); row = sheet.createRow(1); cell = row.createCell(0); cell.setCellValue("This is italic"); cell.setCellStyle(style); try { FileOutputStream out = new FileOutputStream(new File("C:\style.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Code language: Java (java)

Output:

style.xls

java-excel-cell-style

6.1 Add Background Color to the cell

Changing background color of the cell is a bit tricky. Ideally we assume setting background color will have some API like setFillBackgroundColor, but surprisingly to set background color of a cell, we have to set the foreground color :D. See below API.

cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

Code language: Java (java)

So use setFillForegroundColor method to set the background color of given cell. I hope this article is useful.

Понравилась статья? Поделить с друзьями:
  • Excellent skills in excel
  • Excel ячека в ячейке
  • Excel ячейку с формулой скопировать как число
  • Excel ячейку по двум параметрам
  • Excel ячейку защитить от изменения ячейки в excel