最近一个项目需要用到导入、导出Excel功能,周末在家写了个小Demo,顺便记录一下学习
1.导包
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.0.1-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.8-beta5</version>
</dependency>
2.导包之后就可以愉快的玩耍了
2.1导出,如果前台是form表单,那么form的属性enctype="multipart/form-data"需要添加,而不是使用默认的属性
@RequestMapping(value = "/download")
public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
// 创建一个excel
HSSFWorkbook book = new HSSFWorkbook();
// 创建一个工作簿
HSSFSheet sheet = book.createSheet();
sheet.setDefaultColumnWidth((short) 30);
// 创建第一行
HSSFRow row = sheet.createRow((short) 0);
row.setHeightInPoints(15); //设置表头高度
// 第四步,创建表头单元格样式 以及表头的字体样式
HSSFCellStyle style = book.createCellStyle();
style.setWrapText(true);// 设置自动换行
HSSFFont headerFont = book.createFont(); // 创建字体样式
headerFont.setFontName("黑体"); // 设置字体类型
headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
style.setFont(headerFont); // 为标题样式设置字体样式
for (int i = 0; i < 6; i++) {
HSSFCell cell = row.createCell((short) i);
switch (i) {
case 0:
cell.setCellValue("姓名");
break;
case 1:
cell.setCellValue("证件号码");
break;
case 2:
cell.setCellValue("人员类别");
break;
case 3:
cell.setCellValue("人员细类");
break;
case 4:
cell.setCellValue("户籍地区划");
break;
case 5:
cell.setCellValue("详细地址");
break;
}
}
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String("录入人员信息模板1aaa".getBytes(), "iso-8859-1") + ".xls");
book.write(response.getOutputStream());
// 如果转化为字节流:
ByteArrayOutputStream os = new ByteArrayOutputStream();
book.write(os);
byte[] bytes = os.toByteArray();
// 获取响应报文输出流对象
ServletOutputStream out = response.getOutputStream();
// 输出
out.write(bytes);
out.flush();
out.close();
}
2.2导入
@RequestMapping(value = "/upload2", method = RequestMethod.POST)
@ResponseBody
public String upload2Excel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
//获取Excel对象
HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
//获取指定的工作表
HSSFSheet sheet = workbook.getSheetAt(0);
//用来数据的集合
List<Object> list = new ArrayList<>();
//表头那一行
HSSFRow titleRow = sheet.getRow(0);
HSSFCell titleCell = titleRow.getCell((short) 0);
String title = titleCell.getStringCellValue();
HSSFCellStyle title2 = titleCell.getCellStyle();
HSSFRichTextString title3 = titleCell.getRichStringCellValue();
System.out.println(title);
System.out.println(title2);
System.out.println(title3);
return "aaa" + title + ":" + title2 + ":" + title3;
}
说明:这只是一个简单的deno程序,使用的时候需要根据需求自己设置属性值
另外:在使用的时候,还需要判断是.xls还是.xlsx格式的excel两者对应的java类是不一样的,前者对应的是HSSFWorkbook,后者是XssfWorkBook,一般在正常的开发过程中,是通过判断文件的后缀去创建相应的java类,然后对Excel进行相应的操作