一、简介和结构:
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。
本文运用的便是此种方法。
而不同的Poi结构对应不同的操作方法:
HSSF - 提供读写Microsoft Excel XLS格式档案的功能 --xls
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能--xlsx
HWPF - 提供读写Microsoft Word DOC格式档案的功能
HSLF - 提供读写Microsoft PowerPoint格式档案的功能
HDGF - 提供读Microsoft Visio格式档案的功能
HPBF - 提供读Microsoft Publisher格式档案的功能
HSMF - 提供读Microsoft Outlook格式档案的功能
二、导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
三、代码实例
数据的导出:
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
//创建工作簿对象
XSSFWorkbook workbook = new XSSFWorkbook();
//创建工作表对象,指定工作表名称
XSSFSheet sheet = workbook.createSheet("什么表呢");
//创构建第一行
XSSFRow row = sheet.createRow(0);
//设置单元格的宽度
sheet.setDefaultColumnWidth(15);
/*设置单元格的大小
sheet.setColumnWidth(0, 25 * 256);
sheet.setColumnWidth(0, 25 * 256);*/
String[] titleRow = {"订单号", "订单状态", "收货人", "手机号", "地址", "下单时间", "实收金额"};
for (int i = 0; i < titleRow.length; i++) {
//将此段数组设置为表格中每个单元的标题
//creatCell为在每行中创建单元格
row.createCell(i).setCellValue(titleRow[i]);
}
//获取订单数据的集合
List<Orders> list = ordersService.list();
//将集合中的数据设置在每个单元格中
for (int i = 0; i < list.size(); i++) {
XSSFRow row1 = sheet.createRow(i + 1);
row1.createCell(0).setCellValue(list.get(i).getNumber());
row1.createCell(1).setCellValue(list.get(i).getStatus());
row1.createCell(2).setCellValue(list.get(i).getUserName());
row1.createCell(3).setCellValue(list.get(i).getPhone());
row1.createCell(4).setCellValue(list.get(i).getAddress());
row1.createCell(5).setCellValue(String.valueOf(list.get(i).getOrderTime()));
row1.createCell(6).setCellValue(String.valueOf(list.get(i).getAmount()));
}
//设置表格的名称,其中包含时间日期
String filename = "订单明细表" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
// FileOutputStream fileOutputStream = new FileOutputStream("D:\\" + filename);
ServletOutputStream outputStream = response.getOutputStream();
//设置文件的打开方式和mime类型
response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes(), StandardCharsets.UTF_8));
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
效果展示:
从Excel文件读取数据:
//创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook("D:\\hello.xlsx");
//获取工作表,既可以根据工作表的顺序获取,也可以根据工作表的名称获取
XSSFSheet sheet = workbook.getSheetAt(0);
//遍历工作表获得行对象
for (Row row : sheet) {
//遍历行对象获取单元格对象
for (Cell cell : row) {
//获得单元格中的值
String value = cell.getStringCellValue();
System.out.println(value);
}
}
workbook.close();
前端发送的请求:在Vue框架中