Using Adams Excel for data import and export: simplifying complex Excel operations
Import and export Excel files using the Apache POI library
In Java, we can use the Apache POI library to simplify complex Excel operations. Apache POI is a popular Java library used to manipulate files in Microsoft Office format. It provides reading and writing functions for Excel files and is relatively simple and easy to use.
Import Excel data:
Firstly, we need to import the relevant dependencies of the Apache POI library. In the Maven project, the following dependencies can be added to the pom.xml file:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Next, we can use the following code snippet to import data from an Excel file:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelImporter {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code will open an Excel file in the specified path, traverse all rows and columns in the first sheet, and print out the cell contents.
Export Excel data:
You also need to import the dependencies of the Apache POI library. Next, we can use the following code snippet to export the data to an Excel file:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelExporter {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello");
try {
FileOutputStream file = new FileOutputStream("path/to/excel/file.xlsx");
workbook.write(file);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code will create a new Excel workbook and create rows and columns in the first sheet, writing 'Hello' to that cell. Then write the workbook to an Excel file at the specified path.
Using the Apache POI library can simplify complex Excel operations and make data import and export easier to implement. Please note that the file path used in the code example needs to be modified according to the actual situation.