1.Apache POI介绍
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。
maven坐标
<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>
POI结构
- HSSF - 提供读写Microsoft Excel XLS格式档案的功能
- XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能
- HWPF - 提供读写Microsoft Word DOC格式档案的功能
- HSLF - 提供读写Microsoft PowerPoint格式档案的功能
- HDGF - 提供读Microsoft Visio格式档案的功能
- HPBF - 提供读Microsoft Publisher格式档案的功能
- HSMF - 提供读Microsoft Outlook格式档案的功能
2.基本使用
2.1.使用POI从存在的Excel中读取数据
2.2方式二获取行列的值
总结:POI操作将Excel表格封装了几个核心对象
1. XSSFWorkbook
:工作簿
2. XSSFSheet
:工作表
3. Row
:行
4. Cell
:单元格
2.3向Excel文件写入数据
POI工具类的使用
案例:向准备好的Excel模板文件中写入数据,并供下载
1.写入数据到模板
2.供下载
具体代码:
@RequestMapping("/exportBusinessReport")
public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
try {
Map<String, Object> result = reportService.getBusinessReport();
//取出返回结果数据,准备将报表数据写入到Excel文件
String reportDate = (String) result.get("reportDate");
Integer todayNewMember = (Integer) result.get("todayNewMember");
List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
//获得Excel模板文件的绝对路径
String temlateRealPath = request.getSession().getServletContext().getRealPath("teampleate") + File.separator + "report_template.xlsx";
//获取模板文件创建Excel表格对象
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
//获得工作簿
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(2);
row.getCell(5).setCellValue(reportDate);//日期
row = sheet.getRow(4);
row.getCell(5).setCellValue(todayNewMember);
//新增会员数(本日)
row.getCell(7).setCellValue(totalMember);
//总会员数
row = sheet.getRow(5);
row.getCell(5).setCellValue(thisWeekNewMember);
//....
// 本月到诊数
int rowNum = 12;
for (Map map : hotSetmeal) {
// 热门套餐
BigDecimal proportion = (BigDecimal) map.get("proportion");
String name = (String) map.get("name");
Long setmeal_count = (Long) map.get("setmeal_count");
row = sheet.getRow(rowNum++);
row.getCell(4).setCellValue(name);
//套餐名称
row.getCell(5).setCellValue(setmeal_count);
// 预约数量
row.getCell(6).setCellValue(proportion.doubleValue());//占比
}
//通过输出流进行文件下载
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/vnd.mx-excel");
response.setHeader("content-Disposition","attachment;filename=report.xlsx");
workbook.write(out);
out.flush();
out.close();
workbook.close();
return null;
} catch (Exception e) {
e.printStackTrace();
return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
}
}