EasyP0i 一對多數據導入 null值問題
導入Excel格式
后端代碼
- 准備接收數據的實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
@ExcelTarget(value = "question")
public class QuestionExcelDTO implements Serializable {
private static final long serialVersionUID = -548630840115528607L;
/**
* 培訓中心名稱
*/
@Excel(name = "培訓中心", needMerge = true, width = 20)
private String trainingCenterName;
/**
* 題庫分類名稱
*/
@Excel(name = "題庫分類", needMerge = true, width = 35)
private String questionBankCategoryName;
/**
* 題型名稱
*/
@Excel(name = "題型", needMerge = true)
private String questionTypeName;
/**
* 題目難度
*/
@Excel(name = "題目難度", needMerge = true)
private String questionDifficulty;
/**
* 題目內容
*/
@Excel(name = "題目內容", needMerge = true, width = 50)
private String questionContent;
/**
* 選項/答案信息
*/
@ExcelCollection(name = "選項/答案信息")
List<OptionAndAnswer> optionAndAnswerList;
/**
* 答案是否依序(0:否 1:是)
*/
@Excel(name = "答案依序", needMerge = true)
private String orderFlag;
/**
* 試題解析
*/
@Excel(name = "試題解析", needMerge = true, width = 40)
private String questionAnalysis;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ExcelTarget("optionAndAnswer")
public static class OptionAndAnswer implements Serializable {
private static final long serialVersionUID = 7597689935526024438L;
/**
* 選項活答案內容
*/
@Excel(name = "選項/標准答案", width = 40)
private String optionOrAnswerContext;
/**
* 該選項是否為正確答案(“0”:不是 “1”:是)
*/
@Excel(name = "正確答案")
private String trueAnswerFlag;
}
}
- 實現Excel數據導入的方法
@Override
public Message importQuestion(MultipartFile excel) throws Exception {
if (excel == null || excel.isEmpty()) {
return Message.fail("上傳的excel文件不存在");
}
ImportParams importParams = new ImportParams();
importParams.setHeadRows(1);
importParams.setTitleRows(1);
List<QuestionExcelDTO> questionList = null;
questionList = ExcelImportUtil.importExcel(excel.getInputStream(), QuestionExcelDTO.class, importParams);
return null;
}
問題描述
從debug的結果看,存在的解析錯誤有兩點:
1. 導入的Excel表格中的實際數據只有6條,但代碼錯誤的解析出了7條數據,且第一條數據的所有數值均為null;
2. “一對多”數據中的“多”沒有解析出來,全部為null。
問題解決
查看了EasyPoi的官方文檔以后發現,一切的問題出在源代碼中的這條語句:
// 指定表頭所占的行數
importParams.setHeadRows(1);
再來看看剛才導入數據的Excel的表頭:
可以看到表頭的行數應該是2,但是我們設置成了1,將行數設置成2以后再次進行解析:
從解析結果看,問題應該已經得到了解決。