添加poi依赖
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
@ApiOperation(value = "导出Excel")
@PostMapping(value = "/export", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<byte[]> exportToExcel() {
List<Material> materialList = materialService.selectAll();
try(Workbook workbook = new HSSFWorkbook()){
Sheet sheet = workbook.createSheet("Material");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("科目");
headerRow.createCell(1).setCellValue("名称");
headerRow.createCell(2).setCellValue("计量单位");
headerRow.createCell(3).setCellValue("计价方式(元/单位)");
if (materialList.size()>0){
int rowNum = 1;
for(Material material : materialList){
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(material.getSubject());
row.createCell(1).setCellValue(material.getName());
row.createCell(2).setCellValue(material.getUnit());
BigDecimal unitPrice = material.getUnitPrice();
row.createCell(3).setCellValue(String.valueOf(unitPrice));
}
}else {
Row row = sheet.createRow(1);
row.createCell(0).setCellValue("");
row.createCell(1).setCellValue("");
row.createCell(2).setCellValue("");
row.createCell(3).setCellValue("");
}
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
CellRangeAddressList addressList = new CellRangeAddressList(
1, 10000, 0, 0);
DataValidationConstraint dvConstraint = DVConstraint.createExplicitListConstraint(
new String[]{"1.原材料", "2.专用材料", "3.低值易耗品","4.技术资料","5.专业燃料费","6.其他"});
DataValidation validation = dataValidationHelper.createValidation(dvConstraint, addressList);
if(validation instanceof HSSFDataValidation){
validation.setSuppressDropDownArrow(false);
}else{
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
}
sheet.addValidationData(validation);
for(int i = 0; i < headerRow.getLastCellNum(); i++){
sheet.autoSizeColumn(i);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
headers.setContentDisposition(ContentDisposition.builder("attachment")
.filename("material.xls", StandardCharsets.UTF_8)
.build());
return ResponseEntity.ok()
.headers(headers)
.contentLength(bos.size())
.body(bos.toByteArray());
}catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/91e50995e0d4496f86d87542960a4e1f.png)