问题:@Excel()中设置了参数type = 10,导出的Excel中还是文本格式
代码如下:
@Excel(name = "运费",type = 10,isImportField = "true_st")
private BigDecimal freight;
解决办法:
1.新增以下类(原封不动copy到你们项目中,代码中的注释一定要看一下)
代码如下:
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.ss.usermodel.*;
public class ExcelExportStatisticStyler extends ExcelExportStylerDefaultImpl {
private CellStyle numberCellStyle;
public ExcelExportStatisticStyler(Workbook workbook) {
super(workbook);
createNumberCellStyler();
}
private void createNumberCellStyler() {
numberCellStyle = workbook.createCellStyle();
numberCellStyle.setAlignment(HorizontalAlignment.CENTER);
numberCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 这边传的参数格式会影响你导出的数据类型
// "0.00"是自定义类型可以与数字类型直接进行计算,并不是直接导出数字类型
// "#,##0.00" 是货币类型 其他参数到源码查看
numberCellStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("0.00"));
numberCellStyle.setWrapText(true);
}
@Override
public CellStyle getStyles(boolean noneStyler, ExcelExportEntity entity) {
//自定义Dict转换
if (entity != null
&& 10==entity.getType()) {
return numberCellStyle;
}
return super.getStyles(noneStyler, entity);
}
}
2. Controller中调用
代码如下:
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
@PostMapping("/export")
public void exportData(@RequestBody CommonSearch search, HttpServletResponse response) {
try {
// 你需要导出的数据来源
List<AggregateAccountingPOI> list = accountingService.export(search);
// 设置导出参数
ExportParams exportParams = new ExportParams();
// 设置样式 注意这边调用上面自定义的样式类
exportParams.setStyle(ExcelExportStatisticStyler.class);
// 这是直接返回一个Excel 因为我这边前台统一用流处理 所以我多增加了一步转成流返回
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, AggregateAccountingPOI.class, list);
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("你的标题", "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}