1、自定义Converter
package com.example.demo;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* @author xuzhipeng
* @date 2021/11/16
*/
public class CustomFenToYuanConverter implements Converter<Long> {
public CustomFenToYuanConverter() {
}
@Override
public Class<Long> supportJavaTypeKey() {
return Long.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
@Override
public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().longValue();
}
@Override
public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(new BigDecimal(String.valueOf(value)).divide(new BigDecimal(100),2, RoundingMode.HALF_UP), contentProperty);
}
}
2、字段上加注解
package com.example.demo.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.example.demo.CustomFenToYuanConverter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author xuzhipeng
* @date 2021/11/16
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student implements Serializable {
private static final long serialVersionUID = -2276319513977941707L;
@ExcelProperty(value = "金额(元)", index = 0,converter = CustomFenToYuanConverter.class)
@NumberFormat("#0.00")
private Long amount;
}
3、测试
package com.example.demo;
import com.alibaba.excel.EasyExcel;
import com.example.demo.pojo.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* @author xuzhipeng
* @date 2021/9/29
*/
@RestController
public class Controller {
@GetMapping("/hello")
public void hello(HttpServletResponse response) throws Exception {
List<Student> list = new ArrayList<>();
list.add(Student.builder().amount(1234423L).build());
list.add(Student.builder().amount(34455549L).build());
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试文件", "UTF-8") + ".xlsx");
EasyExcel.write(response.getOutputStream(), Student.class).sheet("测试").doWrite(list);
}
}

网友评论