Java Excel处理
本文最后更新于:2024年3月18日 凌晨
Java Excel处理
Apache POI
- Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
- 结构:
- HSSF - 提供读写Microsoft Excel格式档案的功能(Excel 2003 版本)
- XSSF - 提供读写Microsoft Excel OOXML格式档案的功能(Excel 2007 版本)
- HWPF - 提供读写Microsoft Word格式档案的功能。
- HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
- HDGF - 提供读写Microsoft Visio格式档案的功能。
pom.xml
1 2 3 4 5
| <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
|
1 2 3 4 5
| <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency>
|
HSSF
- 提供读写Microsoft Excel格式档案的功能(Excel 2003 版本)
- 缺点:最多只能处理 65536 行,否则会抛出异常。
- 优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快。
Write
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("HSSFWriteTest");
Row row1 = sheet.createRow(0); Cell cell11 = row1.createCell(0); cell11.setCellValue("(1,1)"); Cell cell12 = row1.createCell(1); cell12.setCellValue(1.2);
Row row2 = sheet.createRow(1); Cell cell21 = row2.createCell(0); cell21.setCellValue("(2,1)"); Cell cell22 = row2.createCell(1); cell22.setCellValue(2.2);
FileOutputStream fileOutputStream = new FileOutputStream(PATH + "/HSSFWriteTest.xls"); workbook.write(fileOutputStream); fileOutputStream.close(); }
}
|
Read
基本读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; FileInputStream fileInputStream = new FileInputStream(PATH + "/HSSFWriteTest.xlsx"); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); HSSFSheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); Cell cell = row.getCell(0); System.out.println(cell.getNumericCellValue()); Cell cell1 = row.getCell(1); System.out.println(cell1.getNumericCellValue()); fileInputStream.close(); }
}
|
根据数据类型遍历读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; FileInputStream fileInputStream = new FileInputStream(PATH + "/HSSFWriteTest.xls"); Workbook workbook = new HSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); Row rowTitle = sheet.getRow(0); if (rowTitle != null) { int rowCount = rowTitle.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < rowCount; cellNum++) { Cell cell = rowTitle.getCell(cellNum); if (cell != null) { String cellValue = cell.getStringCellValue(); System.out.print(cellValue + " | "); } } System.out.println(); }
int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 1; rowNum < rowCount; rowNum++) { Row rowData = sheet.getRow(rowNum); if (rowData != null) { int cellCount = rowData.getPhysicalNumberOfCells(); for (int cellNum = 0; cellNum < cellCount; cellNum++) { System.out.print("(" + (rowNum + 1) + "," + (cellNum + 1) + ")");
Cell cell = rowData.getCell(cellNum); if (cell != null) { CellType cellTypeEnum = cell.getCellTypeEnum(); String cellValue = ""; switch (cellTypeEnum) { case STRING: System.out.print("[String]: "); cellValue = cell.getStringCellValue(); break; case BOOLEAN: System.out.print("[BOOLEAN]: "); cellValue = String.valueOf(cell.getBooleanCellValue()); break; case _NONE: System.out.print("[NONE]: "); break; case NUMERIC: System.out.print("[NUMERIC]: "); if (HSSFDateUtil.isCellDateFormatted(cell)) { System.out.print("[数字转换为DATE]: "); Date date = cell.getDateCellValue(); cellValue = new DateTime(date).toString(); } else { System.out.print("[数字转换为字符串输出]: "); cell.setCellType(CellType.STRING); cellValue = cell.toString(); } break; case ERROR: System.out.print("[ERROR]"); break; } System.out.println(cellValue); } } } } fileInputStream.close(); }
}
|
读取公式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; FileInputStream fileInputStream = new FileInputStream(PATH + "/HSSFWriteTest.xls"); Workbook workbook = new HSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(3); Cell cell = row.getCell(0);
FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
CellType cellTypeEnum = cell.getCellTypeEnum(); if (cellTypeEnum == CellType.FORMULA) { System.out.println(cell.getCellFormula()); CellValue evaluate = formulaEvaluator.evaluate(cell); String cellValue = evaluate.formatAsString(); System.out.println(cellValue); } }
}
|
XSSF
- 提供读写Microsoft Excel OOXML格式档案的功能(Excel 2007 版本)
- 缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如 100 万条数据。
- 优点:可以写较大的数据量,如 20 万条。
Write
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; long begin = System.currentTimeMillis(); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); for (int rowNum = 0; rowNum < 65537; rowNum++) { Row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < 10; cellNum++) { Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } FileOutputStream fileOutputStream = new FileOutputStream(PATH + "/XSSFWriteTest.xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); long end = System.currentTimeMillis(); System.out.println((double) (end - begin) / 1000); } }
|
Read
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; FileInputStream fileInputStream = new FileInputStream(PATH + "/XSSFWriteTest.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); XSSFSheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); Cell cell = row.getCell(0); System.out.println(cell.getNumericCellValue()); Cell cell1 = row.getCell(1); System.out.println(cell1.getNumericCellValue()); fileInputStream.close(); }
}
|
SXSSF
- SXSSFWorkbook 来自官方的解释:实现"BigGridDemo” 策略的流式 SXSSFWorkbook 版本,这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。
- 缺点:仍然可能会消耗大量内存,这些内存基于你正在使用的功能,例如合并区域,注释只存储在内存中,因此如果广泛使用,可能需要大量内存。
- 优点:可以写非常大的数据量,如 100 万条甚至更多,写数据速度快,占用更少的内存。
- 注意:过程总会产生临时文件,需要清理临时文件,默认由 100 条记录被保存在内存中,则最前面的数据被写入临时文件,如果想要自定义内存中数据的数量,可以使用
new SXSSFWorkbook(数量)
Write
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; long begin = System.currentTimeMillis(); SXSSFWorkbook workbook = new SXSSFWorkbook(); SXSSFSheet sheet = workbook.createSheet(); for (int rowNum = 0; rowNum < 65537; rowNum++) { Row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < 10; cellNum++) { Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } FileOutputStream fileOutputStream = new FileOutputStream(PATH + "/SXSSFWriteTest.xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); workbook.dispose(); long end = System.currentTimeMillis(); System.out.println((double) (end - begin) / 1000); }
}
|
Read
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Test {
public void ExcelTest() throws IOException { String PATH = "/Users/cian/Downloads"; FileInputStream fileInputStream = new FileInputStream(PATH + "/XSSFWriteTest.xlsx"); SXSSFWorkbook workbook = new SXSSFWorkbook(fileInputStream); SXSSFSheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); Cell cell = row.getCell(0); System.out.println(cell.getNumericCellValue()); Cell cell1 = row.getCell(1); System.out.println(cell1.getNumericCellValue()); fileInputStream.close(); }
}
|
EasyExcel
- EasyExcel 是阿里巴巴开源的一个 excel处理框架,以使用简单,节省内存著称。
- EasyExcel 能大大减少内存占用的主要原因是在解析 Excel 时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。

pom.xml
1 2 3 4 5
| <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.7</version> </dependency>
|
Write
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Data public class DemoData { @ExcelProperty("字符串标题") private String string; @ExcelProperty("日期标题") private Date date; @ExcelProperty("数字标题") private Double doubleData;
@ExcelIgnore private String ignore; }
|
测试写入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class Test {
private List<DemoData> data() { List<DemoData> list = new ArrayList<DemoData>(); for (int i = 0; i < 10; i++) { DemoData data = new DemoData(); data.setString("字符串" + i); data.setDate(new Date()); data.setDoubleData(0.56); list.add(data); } return list; }
public void EasyExcelTest() { String PATH = "/Users/cian/Downloads"; String fileName = PATH + "EasyExcel.xlsx"; EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
String fileName = PATH + "EasyExcel.xlsx"; ExcelWriter excelWriter = null; try { excelWriter = EasyExcel.write(fileName, DemoData.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet("模板").build(); excelWriter.write(data(), writeSheet); } finally { if (excelWriter != null) { excelWriter.finish(); } } }
}
|
Read
监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class DemoDataListener extends AnalysisEventListener<DemoData> {
private static final int BATCH_COUNT = 5; private List<DemoData> list = new ArrayList<DemoData>(); private DemoDAO demoDAO;
@Override public void invoke(DemoData data, AnalysisContext context) { list.add(data); if (list.size() >= BATCH_COUNT) { this.saveData(); list.clear(); } }
@Override public void doAfterAllAnalysed(AnalysisContext context) { saveData(); }
private void saveData() { demoDAO.save(list); } }
|
测试读取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Test {
public void EasyExcelTest() { String fileName = PATH + "EasyExcel.xlsx"; EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
String fileName = PATH + "EasyExcel.xlsx"; ExcelReader excelReader = null; try { excelReader = EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).build(); ReadSheet readSheet = EasyExcel.readSheet(0).build(); excelReader.read(readSheet); } finally { if (excelReader != null) { excelReader.finish(); } } }
}
|