目录
1、POI的三个依赖
XML
<!-- POI的三个依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、控制层代码
java
@RequestMapping("/exportExcel.ctrl")
@ResponseBody
ResponseEntity<byte[]> exportExcel(PlcFirst record) throws UnsupportedEncodingException {
return plcFirstService.exportExcel(record);
}
3、业务层代码
java
public ResponseEntity<byte[]> exportExcel(PlcFirst record) throws UnsupportedEncodingException {
//1、 根据条件查询需要的数据
List<PlcFirst> list = plcFirstMapper.selectPage2(record);
//2、创建一个excel并写入内容
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet=workbook.createSheet("Sheet1");
//3、填写表头
HSSFRow row=sheet.createRow(0);
HSSFCell cell=row.createCell(0);
cell.setCellValue("序列号");
HSSFCell cell1=row.createCell(1);
cell1.setCellValue("工序号");
HSSFCell cell2=row.createCell(2);
cell2.setCellValue("扭矩");
HSSFCell cell3=row.createCell(3);
cell3.setCellValue("角度");
HSSFCell cell4=row.createCell(4);
cell4.setCellValue("OK/NG");
HSSFCell cell5=row.createCell(5);
cell5.setCellValue("工具号");
HSSFCell cell6=row.createCell(6);
cell6.setCellValue("打印码");
HSSFCell cell7=row.createCell(7);
cell7.setCellValue("创建时间");
// 创建日期格式的单元格格式
DataFormat dataFormat = workbook.createDataFormat();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd HH:mm:ss"));
// 4、遍历数据,并写入Excel。
int i=1;
for (PlcFirst plc : list) {
HSSFRow rowi = sheet.createRow(i++);
rowi.createCell(0).setCellValue(plc.getSerNo());
rowi.createCell(1).setCellValue(plc.getGongXuHao());
rowi.createCell(2).setCellValue(plc.getNiuJu());
rowi.createCell(3).setCellValue(plc.getJiaoDu());
rowi.createCell(4).setCellValue(plc.getOkNg());
rowi.createCell(5).setCellValue(plc.getGongJuHao());
rowi.createCell(6).setCellValue(plc.getDaYinMa());
HSSFCell cell77 = rowi.createCell(7);
cell77.setCellValue(plc.getCreateTime());
// 设置单元格格式为日期格式
cell77.setCellStyle(cellStyle);
}
// EEEEE
//创建一个字节数组输出流对象
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
try {
//将excel写入输出流
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
HttpHeaders headers=new HttpHeaders();
String fileName=new String("excel.xls".getBytes("UTF-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> returnFile=new ResponseEntity<byte[]>
(outputStream.toByteArray(),headers,HttpStatus.CREATED);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return returnFile;
}