POI导入导出
POI(Poor Obfuscation Implementation)是Apache的一个开源项目,用来处理Microsoft Office文档。它可以导入和导出Excel、Word、PowerPoint等文件。
导入Excel文件:
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 ExcelReader {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("path_to_your_excel_file.xlsx"));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
case FORMULA:
System.out.print(cell.getCellFormula() + "\t");
break;
default: break;
}
}
System.out.println();
}
workbook.close();
file.close();
}
}
导出Excel文件:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWriter {
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sample Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
FileOutputStream fileOut = new FileOutputStream("path_to_your_excel_file.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
注意:在实际应用中,你需要处理文件路径、错误处理、内存管理等问题。上述代码仅展示了POI的基本使用方法。
评论已关闭