How to use the JXLS Reader tool class and examples
JXLS Reader is an open source Java class library for reading the Microsoft Excel file.It allows developers to use simple APIs to read data in Excel files in the Java application and convert it to Java objects.
Using the JXLS Reader tool class, you can easily read the data of the Excel file in the Java application.Below is an example code using the JXLS Reader tool class:
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReader;
import org.xml.sax.SAXException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class JXLSReaderExample {
public static void main(String[] args) {
try {
// Load the excel file
InputStream inputXML = new FileInputStream("path/to/excel_template.xml");
InputStream inputXLS = new FileInputStream("path/to/excel_data.xls");
// Create a JXLS Reader instance and build a parser
XLSReader reader = ReaderBuilder.buildFromXML(inputXML);
// Prepare data model
Map<String, Object> beans = new HashMap<>();
beans.put("data", new Data());
// Use JXLS Reader to parse the excel file
reader.read(inputXLS, beans);
// Get the data from the data model from the data model
Data data = (Data) beans.get("data");
// The data after the output analysis
System.out.println("Name: " + data.getName());
System.out.println("Age: " + data.getAge());
System.out.println("Email: " + data.getEmail());
// Turn off the input stream
inputXML.close();
inputXLS.close();
} catch (IOException | SAXException e) {
e.printStackTrace();
}
}
}
class Data {
private String name;
private int age;
private String email;
// getter and setter method
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
The above example code demonstrates how to use the JXLS Reader tool class to read the data in the Excel file.First, you need to load the XML configuration and data file of the Excel template file.Then create a JXLS Reader instance and build a parser.Next, prepare a data model object to store data after analysis.Finally, use JXLS Reader to analyze the Excel file and obtain the parsing data from the data model.
This is a simple example that you can customize and expand according to your needs.JXLS Reader provides many senior functions, such as conditional sentences, circulation, and template mapping, which can meet more complex Excel data reading needs.
I hope this article will help you understand the use of the JXLS Reader tool class!