java-EasyExcel export excel to set the cell to text format (including code)

java-EasyExcel export excel to set the cell to text format (including code)

When using EasyExcel to export the excel template. We will find that the exported date and long-length numbers will be automatically changed in format, not in text format. And there is also a problem with the format of entering the date in a blank cell. As shown below, you can see that when the same date is entered, the format will become adaptive, not a text format, so we need to set it from the code and export the form. The cell is fixed to be text (EasyExcel version 2.0+ is used in my project, different versions may have different code implementations, but the principle is the same).
insert image description here

1. Format blank cells as text

Create a new handler to implement the SheetWriteHandler interface, and set the format to text when creating a cell

public class CustomSheetWriteHandler implements SheetWriteHandler {
    
    

    // 设置100列column
    private static final Integer COLUMN = 100;

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    
    

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    
    
        for (int i = 0; i < COLUMN; i++) {
    
    
            // 设置为文本格式
            SXSSFSheet sxssfSheet = (SXSSFSheet) writeSheetHolder.getSheet();
            CellStyle cellStyle = writeWorkbookHolder.getCachedWorkbook().createCellStyle();
            // 49为文本格式
            cellStyle.setDataFormat((short) 49);
            // i为列,一整列设置为文本格式
            sxssfSheet.setDefaultColumnStyle(i, cellStyle);

        }
    }
}

2. Set the format of the cells containing the data as text

Because I found in my own project that if I just complete the first step above, I will find that in the exported template, the format of the cell containing the data is still normal. After re-entering, the date is adaptive again and becomes not a text string. , so I still set the format of the cell containing the data as text

Just add annotations to the fields of the entity class that exports the template: @ContentStyle(dataFormat = 49)

@Data
public class ExpenseTemplateModel {
    
    
   /**
    * 所属年月
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value = "所属年月")
   @ContentStyle(dataFormat = 49)
   private String expenseMonth;
   /**
    * 会计主体
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value = "会计主体")
   @ContentStyle(dataFormat = 49)
   private String borrowerName;
   /**
    * 凭证号
    */
   @HeadStyle(fillForegroundColor = 22)
   @ExcelProperty(value = "凭证号")
   @ContentStyle(dataFormat = 49)
   private String voucherNo;
   /**
    * 摘要
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value = "摘要")
   private String summary;
   /**
    * 科目
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value ="科目")
   private String subjectName;
   /**
    * 部门
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value ="部门")
   private String orgName;
   /**
    * 人员
    */
// @HeadFontStyle(color= 10)
   @HeadStyle(fillForegroundColor = 22)
   @ExcelProperty(value ="人员")
   private String personnel;
   /**
    * 金额
    */
   @HeadFontStyle(color= 10)
   @ExcelProperty(value ="金额")
   @ContentStyle(dataFormat = 49)
   private String amount;
   /**
    * ID号
    */
   @HeadStyle(fillForegroundColor = 22)
   @ExcelProperty(value ="ID号")
   @ContentStyle(dataFormat = 49)
   private String idNo;

   /**
    * 调整类型
    */
   @HeadStyle(fillForegroundColor = 22)
   @ExcelProperty(value ="调整类型")
   private String remark;


}

3. Register the newly created handler class in the first step in the export template

.registerWriteHandler(new CustomSheetWriteHandler())

The following is the implementation class of the exported template for testing:

public void downloadOtherExpenseTemplate(HttpServletResponse response) {
    
    
   List<Remark> remarks = remarkService.listAll(new RemarkQueryBo());

   List<ExpenseTemplateModel> expenseTemplateModels = new ArrayList<>();
   //  添加样例数据
   ExpenseTemplateModel expenseTemplateModel = new ExpenseTemplateModel();
   expenseTemplateModel.setExpenseMonth("2022-09");
   expenseTemplateModel.setBorrowerName("测试有限公司1");
   expenseTemplateModel.setSummary("测试用情况");
   expenseTemplateModel.setSubjectName("测试经费");
   expenseTemplateModel.setOrgName("测试会");
   expenseTemplateModel.setPersonnel("张达达");
   expenseTemplateModel.setAmount("300");
   expenseTemplateModels.add(expenseTemplateModel);
   OutputStream outputStream = null;
   try {
    
    
      String fileName = "测试模板";
      outputStream = response.getOutputStream();
      response.setContentType("multipart/form-data");
      response.setCharacterEncoding("utf-8");
      response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));

      EasyExcel.write(outputStream, ExpenseTemplateModel.class).autoCloseStream(true)
            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
            .registerWriteHandler(new CustomSheetWriteHandler())
            .sheet(fileName).doWrite(expenseTemplateModels);
   } catch (IOException e) {
    
    
      throw new ResultException("导出excel异常: " + e.getMessage());
   } finally {
    
    
      IOUtils.closeQuietly(outputStream);
   }

}

insert image description here

You can see that the format of each cell of the exported template is text.

Guess you like

Origin blog.csdn.net/qq798867485/article/details/129749594