Appearance
How to read and write excel file
There are several ways to read and write Excel files in Java. Here are a few options:
- Apache POI: This is a popular library for reading and writing Microsoft Office file formats, including Excel files. You can find more information and download the library at Apache POI.
- EasyExcel: Developed by Alibaba, this is a modern, lightweight library for reading and writing Excel files in Java. It handles large files efficiently and fully supports XLSX. You can find more information at EasyExcel.
- Google Sheets API: If you want to read and write spreadsheets stored in Google Sheets, you can use the Google Sheets API. You can find more information and documentation for the API at Google Sheets API.
To use any of these libraries, you will need to add the library to your project and import the necessary classes. Then you can use the APIs provided by the library to read and write Excel files.
For example, using Apache POI, you can read an Excel file like this:
java
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
try (FileInputStream file = new FileInputStream("file.xlsx")) {
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
default:
System.out.print("\t\t");
break;
}
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}To write to an Excel file, you can use similar code, but instead of reading cell values, you can set cell values and then write the workbook to a file. For example:
java
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream out = new FileOutputStream("output.xlsx")) {
Sheet sheet = workbook.createSheet("Data");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello Excel");
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}I hope this helps! Let me know if you have any questions.