Java excel to object

I had the same issue, i’ve was aware that the implementation via the standard (Apache POI) why cost so much time so after searching and looking around, i have found a better why (JXLS-Reader)

first of all use/import/include the library jxls-reader

    <dependency>
        <groupId>org.jxls</groupId>
        <artifactId>jxls-reader</artifactId>
        <version>2.0.3</version>
    </dependency>

then create an XML file used by the library for the correspondence between the columns and the your object attributes, this XML take as parameter an initialized list to fill it by extracted data (Employee objects) from the Excel file, in your example, it will look like :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook>
    <worksheet idx="0">
        <section startRow="0" endRow="0" />
        <loop startRow="1" endRow="1" items="employeeList" var="employee" varType="com.department.Employee">
            <section startRow="1" endRow="1">
            <mapping row="1"  col="0">employee.empNo</mapping>
            <mapping row="1"  col="1">employee.empName</mapping>
            </section>
            <loopbreakcondition>
                <rowcheck offset="0">
                    <cellcheck offset="0"></cellcheck>
                </rowcheck>
            </loopbreakcondition>
        </loop>
    </worksheet>
</workbook>

Then in Java, initialize the list of the Employees (where the result of parsing will be included), then call the JXLS reader by the input Excel file and the XML mapping, it will look like:

package com.department;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;


public class ExcelProcessor {

    private static Logger logger = LoggerFactory.getLogger(ExcelProcessor.class);

    public void parseExcelFile(File excelFile) throws Exception{
        final List<Employee> employeeList = new ArrayList<Employee>();
        InputStream xmlMapping = new BufferedInputStream(ExcelProcessor.class.getClassLoader().getResourceAsStream("proBroMapping.xml"));
        ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
        ReaderConfig.getInstance().setSkipErrors(true);
        InputStream inputXLS;
        try{
            XLSReader mainReader = ReaderBuilder.buildFromXML(xmlMapping);
            inputXLS = new BufferedInputStream(new FileInputStream(excelFile));
            final Map<String, Object> beans = new HashMap<String, Object>();
            beans.put("employeeList", employeeList);
            mainReader.read(inputXLS, beans);
            System.out.println("Employee data are extracted successfully from the Excel file, number of Employees is: "+employeeList.size());
        } catch(java.lang.OutOfMemoryError ex){
            // Case of a very large file that exceed the capacity of the physical memory
               ex.printStackTrace();
            throw new Exception(ex.getMessage());
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } catch (SAXException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } catch (InvalidFormatException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

    }

}

Hope this helps anyone having such a problem !

ExcelToObjectMapping-Java

A simple Excel to Object mapper utility using Apache POI.

Usage Example:

Sample excel file (.xlsx):

** Note: Header row must be the first row.**

Name    | Address  |  Number
Ranjit     Mars        123
Foo        Earth       322
Bar        Jupiter     433
Create a sample model class:

** Note: Currently supported data type are: String, Date, int, long, float, double and boolean. If any other data type are provided, value will be not read from excel file. Also, field name must exactly match with excel file header.**

public class Student {
    private String name;
    private String address;
    private int number;
    
    //getters and setters
}
Mapping Excel file to Object:
String file = "/home/ranjit/students.xlsx";
try {
    ExcelToObjectMapper mapper = new ExcelToObjectMapper(file);
    List<Student> students = mapper.map(Student.class);
    for (Student student : students) {
        String res = "Name : " + student.getName() + ", Address : " + student.getAddress() + ", Number : "+ student.getNumber();
        System.out.println(res);
    }
} catch (InvalidExcelFileException e) {
    System.out.println("Invalid Excel file.");
}  catch (FileNotFoundException e) {
    System.out.println("File not found.");
}  catch (InvalidObjectFieldNameException e) {
    System.out.println("Class field name doesnot match with excel file header name.");
} catch (Exception e) {
    System.out.println("Error occured. Unable to execute mapping.");
    e.printStackTrace();
}

 How To Convert Excel Data Into List Of Java Objects : Poiji APIHow to convert excel data into List of Java Objects : Poiji API

Almost every Java developer come across one of the most common requirement expected by the clients. The requirement is working with excel either to generate reports or to take input data from excel. As a java developer, we should be aware of the mapping between excel data & java objects. If we can have an API which can directly map excel cell to a field (property) of a java class, then it will become very easy to implement any kind of operation on excel. No surprise ! We have an API called Poiji(A Java Excel API).

It is developed on top of very popular Apache POI just like Spring Boot on top of Spring. It is available in the maven repository. Thanks to the creator of Poiji !. In fact, we are going to learn it’s implementation in our topic ‘How to convert excel data into List of Java Objects : Poiji API’.

Additionally, the interesting thing is that it uses lots of annotations to make our tasks even easier, just like Spring Boot again. Our main focus in this article will be on “How to convert excel data into List of Java Objects : Poiji API”  but we will learn additional things as well. Equally important, we will implement it using Spring Boot Starter Project. You can also use this concept in excel data upload. Furthermore, let’s get into the topic “How to convert excel data into List of Java Objects : Poiji API” using poiji example now.

What all functionalities/features will you get from this article?

1) How to convert Excel cell values into the List of Java Objects?
2) How to map Excel column with java class properties/variables just like JPA/Hibernate etc…?
3) Additionally, How to use annotation based mapping of excel columns to Model class in java using poiji example?
4) Also, How to save excel data into Database using Spring Boot Data JPA in Spring Boot ?
5) Poiji latest version (currently 3.0.0) has been used to implement the Project.
6) Code is successfully tested on JDK8, JDK9 and JDK14 versions.

What will you learn after implementing this application?

1) How to create a Spring Boot standard application that incorporates industry level back-end project design ?
2) Also, how to design a java application including layers using Entity, Service, Repository etc. as in real time project designs ?
3) Where & how to use Annotations: @ExcelCellName, @ExcelCell, @ExcelRow, @Value, @Autowired, @Service, @Repository, @Entity, @Id, @GeneratedValue etc.
4) Then, working with Runner classes in Spring Boot.
5) Implementation of the Poiji API created on top of the most popular Apache POI(Java API for Microsoft Documents).
6) Also working with application.properties file.
7) How to upload data as a batch into database using Spring Boot?
8) Equally important, How to write modular & reusable code?

9) How to implement dynamic code with minimal changes keeping future change requests in mind?
10) How to write code without hard-coding the values?
11) Last but not the least you will learn ‘How to convert excel data into List of Java Objects : Poiji API’.

What is Poiji ?

Poiji is nothing, but a Java library that programmatically maps excel sheet to Java classes. Moreover, it converts excel rows to a list of Java objects. In other words, it converts each row of the excel data into Java object. Poiji internally uses Apache POI to further process this type of conversion. It is very handy library to convert excel to java object.

Software Used in this project?

Below is the list of software that we have used in this poiji example.

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
♥ MySQL Database : Version ->8.0.19 MySQL Community Server
♦ JDK8 or later versions (Extremely tested on JDK8, JDK9 and JDK14)

External Dependencies

We will add following ‘poiji’ dependency in pom.xml as it is an external jar to get the features of Microsoft Excel.

‘poiji’ dependency in pom.xml

<dependency>
<groupId>com.github.ozlerhakan</groupId>
<artifactId>poiji</artifactId>
<version>3.0.0</version>
</dependency>

Pre-requisites

If you want to store excel data into database, you should already have an existing database. Otherwise, create a MySQL database to save the data. If you just want to test the functionality, then you can use our configurations as database name ‘exceldata’ and table name ‘invoice’.

Coding Steps

Just To test with a poiji example : how Poiji API converts Excel data into List of Objects?

To test the same, we will have only two classes as below:

InvoiceExcel .java


import com.poiji.annotation.ExcelCellName;
import com.poiji.annotation.ExcelRow;

public class InvoiceExcel {

@ExcelRow
private int rowIndex;

@ExcelCellName("Name")
private String name;

@ExcelCellName("Amount")
private Double amount;

@ExcelCellName("Number")
private String number;

@ExcelCellName("RecievedDate")
private String receivedDate;

@Override
public String toString() {
return "InvoiceExcel [rowIndex=" + rowIndex + ", name=" + name + ", amount=" + amount + ", number=" + number
+ ", receivedDate=" + receivedDate + "]";
}

}

ExcelDataToJavaListTest.java

package com.dev.springboot.util;

import java.io.File;
import java.util.List;

import com.poiji.bind.Poiji;

public class ExcelDataToJavaListTest {

public static void main(String[] args) {

File file = new File("D:/ExcelUploadRepo/InvoiceDetailsSheet.xlsx");
List<InvoiceExcel> invoices = Poiji.fromExcel(file, InvoiceExcel.class);
System.out.println("Printing List Data: " +invoices);

}

}

On running above test class, below is the output:

Printing List Data: 
[
InvoiceExcel [rowIndex=1, name=Inv1, amount=3500.0, number=CGP_Inv101, receivedDate=8/30/20],
InvoiceExcel [rowIndex=2, name=Inv2, amount=2424.0, number=BBR_Inv201, receivedDate=8/30/20],
InvoiceExcel [rowIndex=3, name=Inv3, amount=3424.0, number=OGK_Inv304, receivedDate=8/31/20], 
InvoiceExcel [rowIndex=4, name=Inv4, amount=4424.75, number=NKL_Inv345, receivedDate=8/30/20],
InvoiceExcel [rowIndex=5, name=Inv5, amount=5424.0, number=ABC_Inv101, receivedDate=8/29/20]
]

To test how Poiji API converts Excel data into List of Objects and save the data into database?

Step#1 : Create Project in STS

If you are new in Spring Boot go to Internal Link to create a sample project in spring boot. While creating project in STS, add 2 starters ‘MySqL Driver’ and  ‘Spring Data JPA’. You can also add ‘Spring Boot DevTools’ optionally.

Step#2 : Writing classes & updating application.properties

Package/Location
Class/Interface name
Create/Update
Purpose
com.dev.springboot.entity Invoice.java create Entity class to map excel columns and also database tables
com.dev.springboot.repo InvoiceRepository.java create Repository Interface to do database operations
com.dev.springboot.service ExcelPoijiService.java create Interface to implement service
com.dev.springboot.service ExcelPoijiServiceImpl.java create Excel Poiji Service Implementation
com.dev.springboot ExcelDataUploadRunner create Runner class to run logic only once
src/main/resources application.properties update properties file to declare common properties in the project

Below are the codes for each file

application.properties
--------------------------------------------------------------------
#DB Connection Properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/exceldata
spring.datasource.username=root
spring.datasource.password=devs

# Data JPA Properties
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

# Excel file as input for storing it's data
filePath=D:/ExcelUploadRepo/InvoiceDetailsSheet.xlsx

Invoice.java

package com.dev.springboot.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import com.poiji.annotation.ExcelCell;
import com.poiji.annotation.ExcelCellName;

@Entity
public class Invoice {

@Id
@GeneratedValue
private Integer id;

@ExcelCellName("Name") // ("Name") is the column name in excel
private String name;

@ExcelCell(1) // (1) indicates excel column # 1
private Double amount;

@ExcelCell(2) // (2) indicates excel column # 2
private String number;

@ExcelCellName("RecievedDate") // ("RecievedDate") is the column name in excel
private String receivedDate;

}

InvoiceRepository.java (Interface)

package com.dev.springboot.repo;

import org.springframework.data.jpa.repository.JpaRepository;

import com.dev.springboot.entity.Invoice;

public interface InvoiceRepository extends JpaRepository<Invoice, Integer> {

}

ExcelPoijiService.java (Interface)

package com.dev.springboot.service;

import java.util.List;

import com.dev.springboot.entity.Invoice;

public interface ExcelPoijiService {

List<Invoice> getListfromExcelData();

}

ExcelPoijiServiceImpl.java

package com.dev.springboot.service;

import java.io.File;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dev.springboot.entity.Invoice;
import com.poiji.bind.Poiji;

@Service
public class ExcelPoijiServiceImpl implements ExcelPoijiService{

@Value("${filePath}")
public String FILE_PATH;

public List<Invoice> getListfromExcelData() {
File file = new File(FILE_PATH);
List<Invoice> invoices = Poiji.fromExcel(file, Invoice.class);
return invoices;
}
}

ExcelDataUploadRunner.java

package com.dev.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.dev.springboot.repo.InvoiceRepository;
import com.dev.springboot.service.ExcelPoijiService;

@Component
public class ExcelDataUploadRunner implements CommandLineRunner {

@Autowired
InvoiceRepository repo;

@Autowired
ExcelPoijiService excelPoijiService;

@Override
public void run(String... args) {

repo.saveAll(excelPoijiService.getListfromExcelData());
}

}

Once all above files created in STS, your project structure should look similar to below screenshot:

 How To Convert Excel Data Into List Of Java Objects : Poiji API

Running application

In order to run the application, right click on Project and then select Run As >> Spring Boot App.

Testing Results

You can check the saved records into database accordingly, something like below screen:

img_33_excel5

FAQ

How to do our own implementation from this Example with minimal changes?

You need to change values of properties entered in the application.properties file
1) First update the values of first 4 properties as per your database
2) Then update the upload file path with file name in the value of property ‘filePath’

Below are the changes in java files :
3) To store excel records into database you need to create new Entity class and new Repository class in place of ‘Invoice.java’ & ‘InvoiceRepository.java’ accordingly as per your requirements.
4) Then you need to change all occurrences of entity class name used in ‘ExcelPoijiService.java’ and ‘ExcelPoijiServiceImpl.java’ respectively. It’s ‘Invoice’ in our case.
5) Finally interesting thing is that you don’t need to do any change in Runner class ‘ExcelDataUploadRunner.java’

Can we use this implementation in a real project?

Of course, If your project team allows you to use Poiji API, then you can try this implementation in a real project with modification described above as per your requirement.

What are the changes do we need to do if we want to use this functionality in our real project?

In fact, you can go through the minimal modifications suggested in section ‘How to do our own implementation from this Example with minimal changes?’ of this article and you are done.

⇒ Furthermore, If you face any issue on running this project, don’t hesitate to put your comments below. Also, If want to learn more on Poiji API, kindly visit here.

Содержание

  1. How to Write Excel File in Java using POI
  2. Write Excel File in Java using POI – XLS format (2003 or earlier)
  3. Read Excel File in Java using POI – XLSX format (2007 or later)
  4. Convert Java Object To Excel
  5. Other interesting articles which you may like …
  6. Leave a Reply Cancel reply
  7. JavaTechOnline
  8. Making Java Easy To Learn
  9. How to convert excel data into List of Java Objects : Poiji API
  10. What all functionalities/features will you get from this article?
  11. What will you learn after implementing this application?
  12. What is Poiji ?
  13. Software Used in this project?
  14. External Dependencies
  15. Pre-requisites
  16. Coding Steps
  17. Just To test with a poiji example : how Poiji API converts Excel data into List of Objects?
  18. To test how Poiji API converts Excel data into List of Objects and save the data into database?
  19. Step#1 : Create Project in STS
  20. Step#2 : Writing classes & updating application.properties
  21. Running application
  22. Testing Results
  23. How to do our own implementation from this Example with minimal changes?
  24. Can we use this implementation in a real project?
  25. What are the changes do we need to do if we want to use this functionality in our real project?
  26. Работа с Excel в Java через Apache POI
  27. Подготовка: загрузка библиотек и зависимостей
  28. Запись
  29. Чтение

How to Write Excel File in Java using POI

In the previous article, we have learned how to read an Excel file using POI in this article we will learn how to Write Excel File in Java using POI API.

In order to use POI we need to have the following dependencies added in your project.

  • poi-3.15.jar
  • poi-ooxml-3.15.jar
  • poi-ooxml-schemas-3.15.jar
  • xmlbeans-2.6.jar

If you are running on maven add the below dependency to your pom.xml

Write Excel File in Java using POI – XLS format (2003 or earlier)

  • Create a new HSSFWorkbook instance
  • Create a new Worksheet “Football Players”
  • footballPlayers[][] array will hold the array of string which has to be written into the sheet.
  • Iterate each object and create a new row for each object
  • Get the individual cells from the above-created rows and create a new cell using createCell() method
  • Finally, using the write() method of the workbook instance write it into the fileOutputStream and close the workbook.

Output :

You will have the Football.xls created with the below content

Read Excel File in Java using POI – XLSX format (2007 or later)

In order to write XLSX file format we just need to replace HSSF to XSSF in the above code.

Convert Java Object To Excel

In order to convert Java objectTo Excel, we will be writing real-time java object instead of writing String array to the excel. Let’s see how we can achieve this.

Output:

Other interesting articles which you may like …

  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

JavaTechOnline

Making Java Easy To Learn

How to convert excel data into List of Java Objects : Poiji API

  • Spring Boot
  • Excel
  • java
  • poiji

by devs5003 — September 10, 2020 January 26, 2023 2

How to convert excel data into List of Java Objects : Poiji API

Almost every Java developer come across one of the most common requirement expected by the clients. The requirement is working with excel either to generate reports or to take input data from excel. As a java developer, we should be aware of the mapping between excel data & java objects. If we can have an API which can directly map excel cell to a field (property) of a java class, then it will become very easy to implement any kind of operation on excel. No surprise ! We have an API called Poiji(A Java Excel API).

It is developed on top of very popular Apache POI just like Spring Boot on top of Spring. It is available in the maven repository. Thanks to the creator of Poiji !. In fact, we are going to learn it’s implementation in our topic ‘How to convert excel data into List of Java Objects : Poiji API’.

Additionally, the interesting thing is that it uses lots of annotations to make our tasks even easier, just like Spring Boot again. Our main focus in this article will be on “How to convert excel data into List of Java Objects : Poiji API” but we will learn additional things as well. Equally important, we will implement it using Spring Boot Starter Project. You can also use this concept in excel data upload. Furthermore, let’s get into the topic “How to convert excel data into List of Java Objects : Poiji API” using poiji example now.

Table of Contents

What all functionalities/features will you get from this article?

1) How to convert Excel cell values into the List of Java Objects?
2) How to map Excel column with java class properties/variables just like JPA/Hibernate etc…?
3) Additionally, How to use annotation based mapping of excel columns to Model class in java using poiji example?
4) Also, How to save excel data into Database using Spring Boot Data JPA in Spring Boot ?
5) Poiji latest version (currently 3.0.0) has been used to implement the Project.
6) Code is successfully tested on JDK8, JDK9 and JDK14 versions.

What will you learn after implementing this application?

1) How to create a Spring Boot standard application that incorporates industry level back-end project design ?
2) Also, how to design a java application including layers using Entity, Service, Repository etc. as in real time project designs ?
3) Where & how to use Annotations: @ExcelCellName, @ExcelCell, @ExcelRow, @Value, @Autowired, @Service, @Repository, @Entity, @Id, @GeneratedValue etc.
4) Then, working with Runner classes in Spring Boot.
5) Implementation of the Poiji API created on top of the most popular Apache POI(Java API for Microsoft Documents).
6) Also working with application.properties file.
7) How to upload data as a batch into database using Spring Boot?
8) Equally important, How to write modular & reusable code?

9) How to implement dynamic code with minimal changes keeping future change requests in mind?
10) How to write code without hard-coding the values?
11) Last but not the least you will learn ‘How to convert excel data into List of Java Objects : Poiji API’.

What is Poiji ?

Poiji is nothing, but a Java library that programmatically maps excel sheet to Java classes. Moreover, it converts excel rows to a list of Java objects. In other words, it converts each row of the excel data into Java object. Poiji internally uses Apache POI to further process this type of conversion. It is very handy library to convert excel to java object.

Software Used in this project?

Below is the list of software that we have used in this poiji example.

♦ STS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
♥ MySQL Database : Version ->8.0.19 MySQL Community Server
♦ JDK8 or later versions (Extremely tested on JDK8, JDK9 and JDK14)

External Dependencies

We will add following ‘poiji’ dependency in pom.xml as it is an external jar to get the features of Microsoft Excel.

Pre-requisites

If you want to store excel data into database, you should already have an existing database. Otherwise, create a MySQL database to save the data. If you just want to test the functionality, then you can use our configurations as database name ‘exceldata’ and table name ‘invoice’.

Coding Steps

Just To test with a poiji example : how Poiji API converts Excel data into List of Objects?

To test the same, we will have only two classes as below:

On running above test class, below is the output:

To test how Poiji API converts Excel data into List of Objects and save the data into database?

Step#1 : Create Project in STS

If you are new in Spring Boot go to Internal Link to create a sample project in spring boot. While creating project in STS, add 2 starters ‘MySqL Driver’ and ‘Spring Data JPA’. You can also add ‘Spring Boot DevTools’ optionally.

Step#2 : Writing classes & updating application.properties

com.dev.springboot.entity Invoice.java create Entity class to map excel columns and also database tables
com.dev.springboot.repo InvoiceRepository.java create Repository Interface to do database operations
com.dev.springboot.service ExcelPoijiService.java create Interface to implement service
com.dev.springboot.service ExcelPoijiServiceImpl.java create Excel Poiji Service Implementation
com.dev.springboot ExcelDataUploadRunner create Runner class to run logic only once
src/main/resources application.properties update properties file to declare common properties in the project

Below are the codes for each file

Once all above files created in STS, your project structure should look similar to below screenshot:

Running application

In order to run the application, right click on Project and then select Run As >> Spring Boot App.

Testing Results

You can check the saved records into database accordingly, something like below screen:

How to do our own implementation from this Example with minimal changes?

You need to change values of properties entered in the application.properties file
1) First update the values of first 4 properties as per your database
2) Then update the upload file path with file name in the value of property ‘filePath’

Below are the changes in java files :
3) To store excel records into database you need to create new Entity class and new Repository class in place of ‘Invoice.java’ & ‘InvoiceRepository.java’ accordingly as per your requirements.
4) Then you need to change all occurrences of entity class name used in ‘ExcelPoijiService.java’ and ‘ExcelPoijiServiceImpl.java’ respectively. It’s ‘Invoice’ in our case.
5) Finally interesting thing is that you don’t need to do any change in Runner class ‘ExcelDataUploadRunner.java’

Can we use this implementation in a real project?

Of course, If your project team allows you to use Poiji API, then you can try this implementation in a real project with modification described above as per your requirement.

What are the changes do we need to do if we want to use this functionality in our real project?

In fact, you can go through the minimal modifications suggested in section ‘How to do our own implementation from this Example with minimal changes?’ of this article and you are done.

⇒ Furthermore, If you face any issue on running this project, don’t hesitate to put your comments below. Also, If want to learn more on Poiji API, kindly visit here.

Источник

Работа с Excel в Java через Apache POI

Из этой статьи вы сможете узнать о записи и чтении данных из 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.

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

Самое удобное в 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) .

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

Чтение

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

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

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

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

Источник

In the tutorial, Grokonez shows how to convert Excel File to JSON String or JSON File and vice versa with Java language by examples.

– Excel Files: Microsoft Excel is a spreadsheet developed by Microsoft for Windows, macOS, Android and iOS. It features calculation, graphing tools, pivot tables, and a macro programming language called Visual Basic for Applications (VBA). It has been a very widely applied spreadsheet for these platforms
– JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

Dependencies

org.apache.poi: The Apache POI Project’s mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and OLE2 formats and welcome others to participate.
jackson-databind: General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s)

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
</dependency>

We do 2 steps:
– Step 1: Read Excel File into Java List Objects
– Step 2: Convert Java List Objects to JSON String

-> Excel File: customers

convert-excel-file-to-from-json-file-string---excel-file

Customer.java: we create an Java Object class with 4 attributes: id, name, address, age

package com.ozenero.convertexcel2json;

public class Customer {
	private String id;
	private String name;
	private String address;
	private int age;
 
	public Customer() {
	}
 
	public Customer(String id, String name, String address, int age) {
		this.id = id;
		this.name = name;
		this.address = address;
		this.age = age;
	}
 
	public String getId() {
		return id;
	}
 
	public void setId(String id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getAddress() {
		return address;
	}
 
	public void setAddress(String address) {
		this.address = address;
	}
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) {
		this.age = age;
	}
 
	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + "]";
	}
 
}

* Convert Implemetation: we do 2 steps:
– Step 1: Read Excel File into Java List Objects. We use org.apache.poi lib to do the task.
+ Use FileInputStream to get a Excel file.
+ Create a Excel Workbook from FileInputStream.
+ Get an Excel Sheet from above Workbook.
+ Iterate over the Sheet. With each excel row, We get and map the cell-value with each field of Customer object and add to a Customer Object List.
+ Finally, returns all the customer list object.

– Step 2: Convert Java Objects to JSON String
+ Use ObjectMapper to convert List Customer Objects to Json String value.

*** Note: – What is Workbook? -> In Microsoft Excel, a workbook is a collection of one or more spreadsheets, also called worksheets, in a single file.

– Details coding:

package com.ozenero.convertexcel2json;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class ConvertExcel2Json {
	
	public static void main(String[] args) {
		// Step 1: Read Excel File into Java List Objects
		List customers = readExcelFile("customers.xlsx");
		
		// Step 2: Convert Java Objects to JSON String
		String jsonString = convertObjects2JsonString(customers);
		
		System.out.println(jsonString);
	}
	
	/**
	 * Read Excel File into Java List Objects
	 * 
	 * @param filePath
	 * @return
	 */
	private static List readExcelFile(String filePath){
		try {
			FileInputStream excelFile = new FileInputStream(new File(filePath));
    		Workbook workbook = new XSSFWorkbook(excelFile);
     
    		Sheet sheet = workbook.getSheet("Customers");
    		Iterator rows = sheet.iterator();
    		
    		List lstCustomers = new ArrayList();
    		
    		int rowNumber = 0;
    		while (rows.hasNext()) {
    			Row currentRow = rows.next();
    			
    			// skip header
    			if(rowNumber == 0) {
    				rowNumber++;
    				continue;
    			}
    			
    			Iterator cellsInRow = currentRow.iterator();
 
    			Customer cust = new Customer();
    			
    			int cellIndex = 0;
    			while (cellsInRow.hasNext()) {
    				Cell currentCell = cellsInRow.next();
    				
    				if(cellIndex==0) { // ID
    					cust.setId(String.valueOf(currentCell.getNumericCellValue()));
    				} else if(cellIndex==1) { // Name
    					cust.setName(currentCell.getStringCellValue());
    				} else if(cellIndex==2) { // Address
    					cust.setAddress(currentCell.getStringCellValue());
    				} else if(cellIndex==3) { // Age
    					cust.setAge((int) currentCell.getNumericCellValue());
    				}
    				
    				cellIndex++;
    			}
    			
    			lstCustomers.add(cust);
    		}
    		
    		// Close WorkBook
    		workbook.close();
    		
    		return lstCustomers;
        } catch (IOException e) {
        	throw new RuntimeException("FAIL! -> message = " + e.getMessage());
        }
	}
	
	/**
	 * Convert Java Objects to JSON String
	 * 
	 * @param customers
	 * @param fileName
	 */
	private static String convertObjects2JsonString(List customers) {
    	ObjectMapper mapper = new ObjectMapper();
    	String jsonString = "";
    	
    	try {
    		jsonString = mapper.writeValueAsString(customers);
    	} catch (JsonProcessingException e) {
    		e.printStackTrace();
    	}
    	
    	return jsonString; 
	}
}

-> Output, we get a list of customer with Json String format:

[{"id":"1.0","name":"Jack Smith","address":"Massachusetts","age":23},{"id":"2.0","name":"Adam Johnson","address":"New York","age":27},{"id":"3.0","name":"Katherin Carter","address":"Washington DC","age":26},{"id":"4.0","name":"Jack London","address":"Nevada","age":33},{"id":"5.0","name":"Jason Bourne","address":"California","age":36}]

-> Pretty-Printed, we can see more beautiful-printed with below format:

[
  {
    "id": "1.0",
    "name": "Jack Smith",
    "address": "Massachusetts",
    "age": 23
  },
  {
    "id": "2.0",
    "name": "Adam Johnson",
    "address": "New York",
    "age": 27
  },
  {
    "id": "3.0",
    "name": "Katherin Carter",
    "address": "Washington DC",
    "age": 26
  },
  {
    "id": "4.0",
    "name": "Jack London",
    "address": "Nevada",
    "age": 33
  },
  {
    "id": "5.0",
    "name": "Jason Bourne",
    "address": "California",
    "age": 36
  }
]

Excel File to JSON File

We do 2 steps:
– Step 1: Read Excel File into Java List Objects, we do the same above step.
– Step 2: Write Java List Objects to JSON File. We also use the ObjectMapper, but at the case, we write to a Json file not just return a Json String.

-> Detail Coding:

package com.ozenero.convertexcel2json;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertExcel2Json {
	
	public static void main(String[] args) {
		// Step 1: Read Excel File into Java List Objects
		List customers = readExcelFile("customers.xlsx");
		
    	// Step 2: Write Java List Objects to JSON File
    	writeObjects2JsonFile(customers, "customers.json");
    	
    	System.out.println("Done");
	}
	
	/**
	 * Read Excel File into Java List Objects
	 * 
	 * @param filePath
	 * @return
	 */
	private static List readExcelFile(String filePath){
		try {
			FileInputStream excelFile = new FileInputStream(new File(filePath));
    		Workbook workbook = new XSSFWorkbook(excelFile);
     
    		Sheet sheet = workbook.getSheet("Customers");
    		Iterator rows = sheet.iterator();
    		
    		List lstCustomers = new ArrayList();
    		
    		int rowNumber = 0;
    		while (rows.hasNext()) {
    			Row currentRow = rows.next();
    			
    			// skip header
    			if(rowNumber == 0) {
    				rowNumber++;
    				continue;
    			}
    			
    			Iterator cellsInRow = currentRow.iterator();
 
    			Customer cust = new Customer();
    			
    			int cellIndex = 0;
    			while (cellsInRow.hasNext()) {
    				Cell currentCell = cellsInRow.next();
    				
    				if(cellIndex==0) { // ID
    					cust.setId(String.valueOf(currentCell.getNumericCellValue()));
    				} else if(cellIndex==1) { // Name
    					cust.setName(currentCell.getStringCellValue());
    				} else if(cellIndex==2) { // Address
    					cust.setAddress(currentCell.getStringCellValue());
    				} else if(cellIndex==3) { // Age
    					cust.setAge((int) currentCell.getNumericCellValue());
    				}
    				
    				cellIndex++;
    			}
    			
    			lstCustomers.add(cust);
    		}
    		
    		// Close WorkBook
    		workbook.close();
    		
    		return lstCustomers;
        } catch (IOException e) {
        	throw new RuntimeException("FAIL! -> message = " + e.getMessage());
        }
	}
	
    /**
     * 
     * Convert Java Objects to JSON File
     * 
     * @param customers
     * @param pathFile
     */
    private static void writeObjects2JsonFile(List customers, String pathFile) {
        ObjectMapper mapper = new ObjectMapper();

        File file = new File(pathFile);
        try {
            // Serialize Java object info JSON file.
            mapper.writeValue(file, customers);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

JSON String to Excel File

We do 2 steps:
– Convert JSON String to Java List Objects:
+ We use ObjectMapper() and method readValue of it to convert json string to object list.

– Write Java List Objects to Excel File, we use org.apache.poi library:
+ Create a new Excel WorkBook.
+ Create a new Excel Sheet from WorkBook
+ Create Header Row for WorkBook
+ Iterate over Customers Object list, We map each value of customer-object with a corresponding cell of Excel row.

-> Implementation:

package com.ozenero.convertexcel2json;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJson2Excel {
	public static void main(String[] args) throws IOException {
		// Step 1: Read JSON File to List Objects
		String jsonStr = "[{"id":"1","name":"Jack Smith","address":"Massachusetts","age":23},{"id":"2","name":"Adam Johnson","address":"New York","age":27},{"id":"3","name":"Katherin Carter","address":"Washington DC","age":26},{"id":"4","name":"Jack London","address":"Nevada","age":33},{"id":"5","name":"Jason Bourne","address":"California","age":36}]";
		
		List customers = convertJsonString2Objects(jsonStr);
		
    	// Step 2: Convert Java List Objects to JSON File
    	writeObjects2ExcelFile(customers, "customers.xlsx");
	}
	
	/**
	 * 
	 * Convert JSON String to Java List Objects
	 * 
	 * @param pathFile
	 * @return
	 */
	private static List convertJsonString2Objects(String jsonString){
		List customers = null;
		
		try {
			customers = new ObjectMapper().readValue(jsonString, new TypeReference>(){});
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return customers;
	}
	
	/**
	 * 
	 * Write Java Object Lists to Excel File
	 * 
	 * @param customers
	 * @param filePath
	 * @throws IOException 
	 */
	private static void writeObjects2ExcelFile(List customers, String filePath) throws IOException {
		String[] COLUMNs = {"Id", "Name", "Address", "Age"};
		
		Workbook workbook = new XSSFWorkbook();
		 
		CreationHelper createHelper = workbook.getCreationHelper();
 
		Sheet sheet = workbook.createSheet("Customers");
 
		Font headerFont = workbook.createFont();
		headerFont.setBold(true);
		headerFont.setColor(IndexedColors.BLUE.getIndex());
 
		CellStyle headerCellStyle = workbook.createCellStyle();
		headerCellStyle.setFont(headerFont);
 
		// Row for Header
		Row headerRow = sheet.createRow(0);
 
		// Header
		for (int col = 0; col < COLUMNs.length; col++) {
			Cell cell = headerRow.createCell(col);
			cell.setCellValue(COLUMNs[col]);
			cell.setCellStyle(headerCellStyle);
		}
 
		// CellStyle for Age
		CellStyle ageCellStyle = workbook.createCellStyle();
		ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#"));
 
		int rowIdx = 1;
		for (Customer customer : customers) {
			Row row = sheet.createRow(rowIdx++);
 
			row.createCell(0).setCellValue(customer.getId());
			row.createCell(1).setCellValue(customer.getName());
			row.createCell(2).setCellValue(customer.getAddress());
 
			Cell ageCell = row.createCell(3);
			ageCell.setCellValue(customer.getAge());
			ageCell.setCellStyle(ageCellStyle);
		}
 
		FileOutputStream fileOut = new FileOutputStream(filePath);
		workbook.write(fileOut);
		fileOut.close();
		workbook.close();
	}
}

JSON File to Excel File

– Step 1: Read JSON File into Java List Objects
– Step 2: Convert Java List Objects to Excel File

-> Implementation:

package com.ozenero.convertexcel2json;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJson2Excel {
	public static void main(String[] args) throws IOException {
		// Step 1: Read JSON File to List Objects
		List customers = readJsonFile2Objects("customers.json");
		
    	// Step 2: Convert Java List Objects to JSON File
    	writeObjects2ExcelFile(customers, "customers.xlsx");
	}
	
	/**
	 * 
	 * Convert JSON String to Java List Objects
	 * 
	 * @param pathFile
	 * @return
	 */
	private static List readJsonFile2Objects(String pathFile){
		InputStream inJson = Customer.class.getResourceAsStream(pathFile);
		List customers = null;
		
		try {
			customers = new ObjectMapper().readValue(inJson, new TypeReference>(){});
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return customers;
	}
	
	/**
	 * 
	 * Write Java Object Lists to Excel File
	 * 
	 * @param customers
	 * @param filePath
	 * @throws IOException 
	 */
	private static void writeObjects2ExcelFile(List customers, String filePath) throws IOException {
		String[] COLUMNs = {"Id", "Name", "Address", "Age"};
		
		Workbook workbook = new XSSFWorkbook();
		 
		CreationHelper createHelper = workbook.getCreationHelper();
 
		Sheet sheet = workbook.createSheet("Customers");
 
		Font headerFont = workbook.createFont();
		headerFont.setBold(true);
		headerFont.setColor(IndexedColors.BLUE.getIndex());
 
		CellStyle headerCellStyle = workbook.createCellStyle();
		headerCellStyle.setFont(headerFont);
 
		// Row for Header
		Row headerRow = sheet.createRow(0);
 
		// Header
		for (int col = 0; col < COLUMNs.length; col++) {
			Cell cell = headerRow.createCell(col);
			cell.setCellValue(COLUMNs[col]);
			cell.setCellStyle(headerCellStyle);
		}
 
		// CellStyle for Age
		CellStyle ageCellStyle = workbook.createCellStyle();
		ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#"));
 
		int rowIdx = 1;
		for (Customer customer : customers) {
			Row row = sheet.createRow(rowIdx++);
 
			row.createCell(0).setCellValue(customer.getId());
			row.createCell(1).setCellValue(customer.getName());
			row.createCell(2).setCellValue(customer.getAddress());
 
			Cell ageCell = row.createCell(3);
			ageCell.setCellValue(customer.getAge());
			ageCell.setCellStyle(ageCellStyle);
		}
 
		FileOutputStream fileOut = new FileOutputStream(filePath);
		workbook.write(fileOut);
		fileOut.close();
		workbook.close();
	}
}

— Project Structure:

convert-excel-file-to-from-json-file-string---project-structure

This article shows you how can you convert an Excel file to JSON using Apache POI. The Apache POI is a pure java library to work with various Microsoft documents. Today we will show you the Excel to JSON Converter in java by using the POI and the Jackson JSON library. If you want to do this conversion without using Apache poi, read this article: Convert Excel file data to JSON in Javascript.

To convert excel files to JSON, we will use the below two Java libraries here:

  1. Apache POI – to read the excel file data.
  2. Jackson JSON – to parse the excel file data into JSON format.

Apache POI

Apache POI is an API provided by Apache Software Foundation for manipulating various file formats based upon Microsoft’s OLE2 Compound Document Format (OLE2) and Office Open XML standards (OOXML). Click here to know more about Apache POI. In order to work with the Apache POI library, you can use either maven dependency or poi jars.

Apache POI Maven Dependency

If you want to create a maven application, then you can add the below maven dependency into the pom.xml file.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>

NOTE:

If you want to work with only XLS file, then the first dependency is enough but if you want to work with both XLS or XLSX then you have to use both dependencies.

Apache POI Jars

If you are going to create a non-maven application, then you can use the below jar files directly in classpath:

  1. poi-4.0.1.jar
  2. poi-ooxml-4.0.1.jar
  3. poi-ooxml-schemas-4.0.1.jar
  4. xmlbeans-3.0.2.jar
  5. curvesapi-1.05.jar
  6. commons-codec-1.11.jar
  7. commons-collections4-4.2.jar
  8. commons-compress-1.18.jar
  9. commons-math3-3.6.1.jar

You can easily download all the above jars in one place: download Jars here.

download apache poi jars

If you want to know the complete Apache POI setups process in Eclipse IDE, visit another article Apache POI – Getting Started.

Jackson JSON

Jackson is a very popular, lightweight, and high-performance library in java to serialize or map java objects to JSON and vice versa. In order to use this library in the maven application, you can add the below dependency into the pom.xml file.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.13.2</version>
		</dependency>

Excel to json converter example in Java

Here we will see an example to convert an excel file to JSON object in java using the POI and Jackson JSON library. This example program will work for both Excel file formats XLS and XLSX.

package com.javacodepoint.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * 
 * @author javacodepoint.com
 *
 */
public class ExcelToJSONConverter {

	private ObjectMapper mapper = new ObjectMapper();

	/**
	 * Method to convert excel sheet data to JSON format
	 * 
	 * @param excel
	 * @return
	 */
	public JsonNode excelToJson(File excel) {
		// hold the excel data sheet wise
		ObjectNode excelData = mapper.createObjectNode();
		FileInputStream fis = null;
		Workbook workbook = null;
		try {
			// Creating file input stream
			fis = new FileInputStream(excel);

			String filename = excel.getName().toLowerCase();
			if (filename.endsWith(".xls") || filename.endsWith(".xlsx")) {
				// creating workbook object based on excel file format
				if (filename.endsWith(".xls")) {
					workbook = new HSSFWorkbook(fis);
				} else {
					workbook = new XSSFWorkbook(fis);
				}

				// Reading each sheet one by one
				for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
					Sheet sheet = workbook.getSheetAt(i);
					String sheetName = sheet.getSheetName();

					List<String> headers = new ArrayList<String>();
					ArrayNode sheetData = mapper.createArrayNode();
					// Reading each row of the sheet
					for (int j = 0; j <= sheet.getLastRowNum(); j++) {
						Row row = sheet.getRow(j);
						if (j == 0) {
							// reading sheet header's name
							for (int k = 0; k < row.getLastCellNum(); k++) {
								headers.add(row.getCell(k).getStringCellValue());
							}
						} else {
							// reading work sheet data
							ObjectNode rowData = mapper.createObjectNode();
							for (int k = 0; k < headers.size(); k++) {
								Cell cell = row.getCell(k);
								String headerName = headers.get(k);
								if (cell != null) {
									switch (cell.getCellType()) {
									case FORMULA:
										rowData.put(headerName, cell.getCellFormula());
										break;
									case BOOLEAN:
										rowData.put(headerName, cell.getBooleanCellValue());
										break;
									case NUMERIC:
										rowData.put(headerName, cell.getNumericCellValue());
										break;
									case BLANK:
										rowData.put(headerName, "");
										break;
									default:
										rowData.put(headerName, cell.getStringCellValue());
										break;
									}
								} else {
									rowData.put(headerName, "");
								}
							}
							sheetData.add(rowData);
						}
					}
					excelData.set(sheetName, sheetData);
				}
				return excelData;
			} else {
				throw new IllegalArgumentException("File format not supported.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (workbook != null) {
				try {
					workbook.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return null;
	}

	/**
	 * Main method to test this converter
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		// Creating a file object with specific file path
		File excel = new File("E:/Excel/employee.xlsx");
		ExcelToJSONConverter converter = new ExcelToJSONConverter();
		JsonNode data = converter.excelToJson(excel);
		System.out.println("Excel file contains the Data:n" + data);

	}
}

How to write JSON data into text file in java?

Now, if you want to write the converted JSON object into a file, then you can use the below method:

/**
	 * Method to write the json data into file
	 * 
	 * @param jsonFile
	 * @param jsonData
	 */
	public boolean writeJsonToFile(File jsonFile, JsonNode jsonData) {
		try {
			if (jsonFile.getName().endsWith(".json")) {
				if (!jsonFile.exists()) {
					jsonFile.createNewFile();
				}
				FileWriter fw = new FileWriter(jsonFile);
				fw.write(jsonData.toPrettyString());
				fw.close();
				return true;
			} else {
				throw new IllegalArgumentException("File should be .json file only");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

Conclusion

In this article, you have seen how do you Convert Excel files to JSON in java using the Apache POI and Jackson JSON libraries. If you want to do this in javascript, visit another article here: Convert Excel file data to JSON in Javascript.

You can download the above example (maven application zip) from the below download link.

FAQ

How to convert xls to JSON?

You can use the above example program to convert xls to JSON. In this case, you can use only one maven dependency which is poi-4.0.1

How to convert xlsx to JSON?

For this converter also you can use the above example program, but make sure that you use both maven dependencies (poi-4.0.1 and poi-ooxml-4.0.1).

Related Articles:

  • Convert JSON to Excel in Java [Source Code]
  • [Java code] Convert CSV to Excel file using Apache POI
  • [Java code] Convert Excel file to CSV with Apache POI
  • Apache POI – Read and Write Excel files in java
  • How to write data to an existing Excel file in java?
  • How to create password-protected Excel in java?

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. In this article, we are going to discuss how to write the data from an Excel file into a HashMap in java using Apache POI. HashMap is a type of collection in Java that contains a key-value pair for storing the data. Apache POI is an open-source Java library for manipulating Microsoft documents like Excel, word, etc.

    Pre-Requisite

    To work with this example, we need the following:

    • Java installed in your system, for installing java check this article.
    • Also Install the Eclipse IDE for Java Developers here.
    • After that, create a Maven Project

    For creating a Maven project refer to this How to Create a Selenium Maven Project with Eclipse to Open Chrome Browser?

    • Add the dependency for Apache POI and Apache-ooxml in the POM.xml file
    • Go to the MVN repository https://mvnrepository.com/.
    • Search for the Apache POI

    • Copy and paste these dependencies into the pom.xml then save it.

    Let’s discuss this with an example, now create an Excel file with some data on it, we have to read the data from this file and write it into the HashMap. Let’s see this Example with hands-on coding.

    Program for writing Data from Excel file into a HashMap

    Java

    package GFG_Maven.GFG_MAven;

    import java.io.FileInputStream;

    import java.io.IOException;

    import java.util.HashMap;

    import java.util.Iterator;

    import java.util.Map;

    import java.util.Map.Entry;

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

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

    import org.testng.annotations.Test;

    public class Geeks {

        @Test public void geekforgeeks() throws IOException

        {

            FileInputStream file = new FileInputStream(

                "C:\Users\ADMIN\Desktop\data.xlsx");

            XSSFWorkbook wb = new XSSFWorkbook(file);

            XSSFSheet sh = wb.getSheet("Sheet1");

            HashMap<Integer, String> map

                = new HashMap<Integer, String>();

            for (int r = 0; r <= sh.getLastRowNum(); r++) {

                int key = (int)sh.getRow(r)

                              .getCell(0)

                              .getNumericCellValue();

                String value = sh.getRow(r)

                                   .getCell(1)

                                   .getStringCellValue();

                map.put(key, value);

            }

            Iterator<Entry<Integer, String> > new_Iterator

                = map.entrySet().iterator();

            while (new_Iterator.hasNext()) {

                Map.Entry<Integer, String> new_Map

                    = (Map.Entry<Integer, String>)

                          new_Iterator.next();

                System.out.println(new_Map.getKey() + "|"

                                   + new_Map.getValue());

            }

            wb.close();

            file.close();

        }

    }

    Code Explanation

    • Open the file in the input stream.
    • Create the workbook and get the sheet for that Excel.
    • Declare the HashMap for storing the data from Excel.
    • Iterate through the Rows to get the Key and value data.
    • Add the data into the HashMap using the put method.
    • For displaying HashMap iterate through the map and print the output.

    Output

    After executing the above code we will get all the data in the Excel stored in HashMap and it is printed.

    Output

    Like Article

    Save Article

    A reader of the article Read / Write Excel Data Using Apache POI asks me a question about how to read excel sheet data and write those data to a JSON file. This question lead to this example. So after reading this article you can know how to convert excel sheet data to a JSON file, and how to create a text file that contains the excel sheet data.

    1. Convert Excel To JSON Example Required Library.

    This example requires the below jar files, you can go to the maven repository to search and download them if you add the jars by hand. You can read the article How To Download Jars From Maven Repository to learn more.

    1. commons-beanutils-1.8.3.jar
    2. ezmorph-1.0.6.jar
    3. commons-collections-3.2.1.jar
    4. commons-lang-2.6.jar
    5. json-lib-2.4.jar
    6. apache-poi-maven-lib
    7. poi-bin-3.16-20170419.zip

    Because this example uses apache poi to parse excel files, so all the poi-related jar files are included in the poi-bin zip file. Just download it and unzip it to get those jars.

    2. Convert Excel To JSON Example Source Code.

    1. Below is the example source code that can convert an excel file to a JSON file.
      package com.dev2qa.java.basic.excel;
      
      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.FileWriter;
      import java.io.IOException;
      import java.math.BigDecimal;
      import java.util.ArrayList;
      import java.util.List;
      
      import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      import org.apache.poi.ss.usermodel.Row;
      import org.apache.poi.ss.usermodel.Cell;
      import org.apache.poi.ss.usermodel.CellType;
      import org.apache.poi.ss.usermodel.Header;
      import org.apache.poi.ss.usermodel.Sheet;
      import org.apache.poi.ss.usermodel.Workbook;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;
      import org.openqa.selenium.json.Json;
      
      import com.google.gson.Gson;
      import com.google.gson.stream.JsonReader;
      
      import net.sf.json.JSONObject;
      
      public class ReadExcelDataWithDynamicColumn {
      
          public static void main(String[] args)
          {
              // You can specify your excel file path.
              String excelFilePath = "/Users/zhaosong/Documents/WorkSpace/EmployeeInfo.xls";
      
              // This method will read each sheet of data from the above excel file and create a JSON and a text file to save the sheet data.
              creteJSONAndTextFileFromExcel(excelFilePath);
          }
      
      
          /* Read data from an excel file and output each sheet of data to a JSON file and a text file. 
           * filePath:  The excel file store path.
           * */
          private static void creteJSONAndTextFileFromExcel(String filePath)
          {
              try{
               /* First need to open the file. */
                  FileInputStream fInputStream = new FileInputStream(filePath.trim());
         
               /* Create the workbook object to access excel file. */
                  //Workbook excelWookBook = new XSSFWorkbook(fInputStream)
               /* Because this example use .xls excel file format, so it should use HSSFWorkbook class. For .xlsx format excel file use XSSFWorkbook class.*/;
                  Workbook excelWorkBook = new HSSFWorkbook(fInputStream);
      
                  // Get all excel sheet count.
                  int totalSheetNumber = excelWorkBook.getNumberOfSheets();
      
                  // Loop in all excel sheet.
                  for(int i=0;i<totalSheetNumber;i++)
                  {
                      // Get current sheet.
                      Sheet sheet = excelWorkBook.getSheetAt(i);
      
                      // Get sheet name.
                      String sheetName = sheet.getSheetName();
      
                      if(sheetName != null && sheetName.length() > 0)
                      {
                          // Get current sheet data in a list table.
                          List<List<String>> sheetDataTable = getSheetDataList(sheet);
      
                          // Generate JSON format of above sheet data and write to a JSON file.
                          String jsonString = getJSONStringFromList(sheetDataTable);
                          String jsonFileName = sheet.getSheetName() + ".json";
                          writeStringToFile(jsonString, jsonFileName);
      
                          // Generate text table format of above sheet data and write to a text file.
                          String textTableString = getTextTableStringFromList(sheetDataTable);
                          String textTableFileName = sheet.getSheetName() + ".txt";
                          writeStringToFile(textTableString, textTableFileName);
      
                      }
                  }
                  // Close excel work book object. 
                  excelWorkBook.close();
              }catch(Exception ex){
                  System.err.println(ex.getMessage());
              }
          }
      
      
          /* Return sheet data in a two-dimensional list. 
           * Each element in the outer list is represent a row, 
           * each element in the inner list represent a column.
           * The first row is the column name row.*/
          private static List<List<String>> getSheetDataList(Sheet sheet)
          {
              List<List<String>> ret = new ArrayList<List<String>>();
      
              // Get the first and last sheet row number.
              int firstRowNum = sheet.getFirstRowNum();
              int lastRowNum = sheet.getLastRowNum();
      
              if(lastRowNum > 0)
              {
                  // Loop in sheet rows.
                  for(int i=firstRowNum; i<lastRowNum + 1; i++)
                  {
                      // Get current row object.
                      Row row = sheet.getRow(i);
      
                      // Get first and last cell number.
                      int firstCellNum = row.getFirstCellNum();
                      int lastCellNum = row.getLastCellNum();
      
                      // Create a String list to save column data in a row.
                      List<String> rowDataList = new ArrayList<String>();
      
                      // Loop in the row cells.
                      for(int j = firstCellNum; j < lastCellNum; j++)
                      {
                          // Get current cell.
                          Cell cell = row.getCell(j);
      
                          // Get cell type.
                          int cellType = cell.getCellType();
      
                          if(cellType == CellType.NUMERIC.getCode())
                          {
                              double numberValue = cell.getNumericCellValue();
      
                              // BigDecimal is used to avoid double values is counted using the Scientific counting method.
                              // For example the original double variable value is 12345678, but JDK translated the value to 1.2345678E7.
                              String stringCellValue = BigDecimal.valueOf(numberValue).toPlainString();
      
                              rowDataList.add(stringCellValue);
      
                          }else if(cellType == CellType.STRING.getCode())
                          {
                              String cellValue = cell.getStringCellValue();
                              rowDataList.add(cellValue);
                          }else if(cellType == CellType.BOOLEAN.getCode())
                          {
                              boolean numberValue = cell.getBooleanCellValue();
      
                              String stringCellValue = String.valueOf(numberValue);
      
                              rowDataList.add(stringCellValue);
      
                          }else if(cellType == CellType.BLANK.getCode())
                          {
                              rowDataList.add("");
                          }
                      }
      
                      // Add current row data list in the return list.
                      ret.add(rowDataList);
                  }
              }
              return ret;
          }
      
          /* Return a JSON string from the string list. */
          private static String getJSONStringFromList(List<List<String>> dataTable)
          {
              String ret = "";
      
              if(dataTable != null)
              {
                  int rowCount = dataTable.size();
      
                  if(rowCount > 1)
                  {
                      // Create a JSONObject to store table data.
                      JSONObject tableJsonObject = new JSONObject();
      
                      // The first row is the header row, store each column name.
                      List<String> headerRow = dataTable.get(0);
      
                      int columnCount = headerRow.size();
      
                      // Loop in the row data list.
                      for(int i=1; i<rowCount; i++)
                      {
                          // Get current row data.
                          List<String> dataRow = dataTable.get(i);
      
                          // Create a JSONObject object to store row data.
                          JSONObject rowJsonObject = new JSONObject();
      
                          for(int j=0;j<columnCount;j++)
                          {
                              String columnName = headerRow.get(j);
                              String columnValue = dataRow.get(j);
      
                              rowJsonObject.put(columnName, columnValue);
                          }
      
                          tableJsonObject.put("Row " + i, rowJsonObject);
                      }
      
                      // Return string format data of JSONObject object.
                      ret = tableJsonObject.toString();
      
                  }
              }
              return ret;
          }
      
      
          /* Return a text table string from the string list. */
          private static String getTextTableStringFromList(List<List<String>> dataTable)
          {
              StringBuffer strBuf = new StringBuffer();
      
              if(dataTable != null)
              {
                  // Get all row count.
                  int rowCount = dataTable.size();
      
                  // Loop in the all rows.
                  for(int i=0;i<rowCount;i++)
                  {
                      // Get each row.
                      List<String> row = dataTable.get(i);
      
                      // Get one row column count.
                      int columnCount = row.size();
      
                      // Loop in the row columns.
                      for(int j=0;j<columnCount;j++)
                      {
                          // Get column value.
                          String column = row.get(j);
      
                          // Append column value and a white space to separate value.
                          strBuf.append(column);
                          strBuf.append("    ");
                      }
      
                      // Add a return character at the end of the row. 
                      strBuf.append("rn");
                  }
      
              }
              return strBuf.toString();
          }
      
          /* Write string data to a file.*/
          private static void writeStringToFile(String data, String fileName)
          {
              try
              {
                  // Get the currently executing class working directory.
                  String currentWorkingFolder = System.getProperty("user.dir");
      
                  // Get file path separator.
                  String filePathSeperator = System.getProperty("file.separator");
      
                  // Get the output file absolute path.
                  String filePath = currentWorkingFolder + filePathSeperator + fileName;
      
                  // Create File, FileWriter, and BufferedWriter object.
                  File file = new File(filePath);
      
                  FileWriter fw = new FileWriter(file);
      
                  BufferedWriter buffWriter = new BufferedWriter(fw);
      
                  // Write string data to the output file, flush and close the buffered writer object.
                  buffWriter.write(data);
      
                  buffWriter.flush();
      
                  buffWriter.close();
      
                  System.out.println(filePath + " has been created.");
      
              }catch(IOException ex)
              {
                  System.err.println(ex.getMessage());
              }
          }
      }

    Понравилась статья? Поделить с друзьями:
  • Java excel cell format
  • Javascript and excel vba
  • Java download to excel
  • Java чтение word файла
  • Java create word document