最近有個(gè)需求使用EXCEL導(dǎo)入數(shù)據(jù),插入數(shù)據(jù)庫之前會(huì)有一系列校驗(yàn),其中沒有通過校驗(yàn)的需要把那個(gè)字段在EXCEL中置紅,并且填充失敗原因后導(dǎo)出,但是在網(wǎng)上找了很久沒有教學(xué)怎樣使用hutool.poi.excel實(shí)現(xiàn)的,官網(wǎng)也只是描述了有這個(gè)功能,但是具體怎么使用沒有闡述。
有兩種方式實(shí)現(xiàn)這個(gè)功能:
第一種是使用ExcelWriter.write()方法先把EXCEL寫出來(還沒有生成文件,只是寫到了sheet里面),然后循環(huán)遍歷使用ExcelWriter.setStyle(CellStyle style, int x, int y)方法來設(shè)置你想要的單元格格式(比如說字體置紅),其中X是列(及表頭屬性個(gè)數(shù)),Y是行(及有多少條數(shù)據(jù)),要注意Y是從1開始遍歷(因?yàn)?是表示)
實(shí)體類,其中@Alias是hutool的注解,用于表頭名稱
public class EmployeeExcelRow {
@Alias("姓名")
private String name;
@Alias("手機(jī)號(hào)")
private String mobile;
@Alias("門店")
private String storeList;
@Alias("角色")
private String roleList;
@Alias("是否禁用")
private String disableStatus;
}
導(dǎo)出簡(jiǎn)易代碼
//這個(gè)路徑是C/user目錄下的,也可以自己寫
String fileName = System.getProperty("user.home") + File.separator + "職員列表-" + RandomUtils.getUUId() + ".xlsx";
try (ExcelWriter excelWriter =ExcelUtil.getWriter(fileName){
……
List<EmployeeExcelRow> prescriptionExcelRows =prescriptionService.getPrescriptionList();
……
excelWriter.write(prescriptionExcelRows)
//x就是實(shí)體類屬性的個(gè)數(shù)
for(int x=0;x<6;x++){
//去掉第一行,也就是表頭
int y=1;
//定義單元格的屬性,這里只是定義了字體為紅色
CellStyle redStyle=excelWriter.createCellStyle(x,y);
Font redFont = excelWriter.createFont();
redFont.setColor(Font.COLOR_RED);
redStyle.setFont(redFont);
y++;
}
}
第二種為一行一行寫,不推薦。