關於java的Excel匯入匯出之easypoi
阿新 • • 發佈:2021-08-30
-
匯入easypoi相關jar包,這裡的easypoi-base的包也可以不倒入,因為easypoi-web中有依賴easypoi-base會自動匯入的
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-base --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-annotation --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>4.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-web --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>4.2.0</version> </dependency>
-
編寫匯出使用的Javabean,根據具體的需求來定。
//匯出實體類的唯一標識 @ExcelTarget("EcCommodityManagementExport") //提供get、set @Data //實現序列化 public class EcCommodityManagementExportVo implements Serializable { private static final long serialVersionUID = 42L; /** * 圖片 ,此處做的第一列與第二列的列名合併(只是列名合併),因為合併之後是第一列的值作為新值填充所以與第二列 * 的name一樣 * name 匯出時的列名名稱 * type 匯出型別 1 是文字 2 是圖片,3 是函式,10 是數字 預設是文字 * imageType 匯出型別 1 從file讀取 2 是從資料庫中讀取 預設是檔案 同樣匯入也是一樣的 * numFormat 數字格式化,引數是Pattern,使用的物件是DecimalFormat * replace 值得替換 匯出是{a_id,b_id} 匯入反過來,所以只用寫一個 * databaseFormat 匯出時間設定,如果欄位是Date型別則不需要設定 資料庫如果是string 型別,這個需要設定這個數 * 據庫格式 */ @Excel(name = "商品名稱(規格描述、單位)" , type = 2 , imageType = 1 , height = 54 , width = 25) private String picUrl; /** * 商品名稱 */ @Excel(name = "商品名稱(規格描述、單位)" , height = 54 , width = 25) private String productName; /** * 商品編碼 */ @Excel(name = "商品編碼" , height = 54 , width = 25) private String productCode; /** * 原價 */ @Excel(name = "原價" , height = 54 , width = 25 , numFormat = "0.00") private BigDecimal primeCost; /** * 售價 */ @Excel(name = "售價" , height = 54 , width = 25 , numFormat = "0.00") private BigDecimal price; /** * 庫存 */ @Excel(name = "庫存" , height = 54 , width = 25) private int repertory; /** * 商品狀態(0未提交1已提交2已上架3已下架) */ @Excel(name = "商品狀態" , height = 54 , width = 25 , replace = {"未提交_0","已提交_1","已上架_2","已下架_3"}) private int productStatus; /** * 上架時間 */ @Excel(name = "上架時間" , height = 54 , width = 25 , databaseFormat = "yyyy-MM-dd HH:mm:ss" , format = "yyyy-MM-dd HH:mm:ss") private String addedTime; /** * 稽核狀態(0--1未稽核2稽核成功3稽核失敗) */ @Excel(name = "稽核狀態" , height = 54 , width = 25 , replace = {"--_0","未稽核_1","稽核成功_2","稽核失敗_3"}) private int auditStatus; /** * 稽核人姓名 */ @Excel(name = "稽核人姓名" , height = 54 , width = 25) private String auditUserName; /** * 建立人姓名 */ @Excel(name = "建立人姓名" , height = 54 , width = 25) private String createUserName; /** * 建立時間 */ @Excel(name = "建立時間" , height = 54 , width = 25 , databaseFormat = "yyyy-MM-dd HH:mm:ss" , format = "yyyy-MM-dd HH:mm:ss") private Date createTime; }
-
編寫匯出控制層程式碼
@ApiOperation(value = "匯出" , notes = "匯出") @GetMapping("exportProduct") public void exportProduct(@RequestParam("productIdList") List<String> productIdList, HttpServletRequest request, HttpServletResponse response) throws Exception{ ecCommodityManagementService.exportProduct(productIdList,request,response); }
-
編寫匯出業務層程式碼
/** * 匯出 * @param productIdList * @param request * @param response */ @Override public void exportProduct(List<String> productIdList, HttpServletRequest request, HttpServletResponse response) throws Exception{ //如果勾選商品則查詢勾選的資料,如沒有勾選則查所有商品資料 List<EcCommodityManagementExportVo> ecCommodityManagementList = ecCommodityManagementMapper.findExportData(productIdList); if (ecCommodityManagementList != null && ecCommodityManagementList.size() > 0){ //封裝圖片資料 for (EcCommodityManagementExportVo ecCommodityManagementExportVo : ecCommodityManagementList) { //匯出圖片時如果是連結形式要填寫全路徑 ecCommodityManagementExportVo.setPicUrl(fileUrl + ecCommodityManagementExportVo.getPicUrl()); } } //設定匯出檔案表頭及sheet名 ExportParams exportParams = new ExportParams("商品列表", "商品列表"); //設定匯出型別為Excel exportParams.setType(ExcelType.XSSF); //建立資料匯出物件 Workbook workbook = ExcelExportUtil.exportExcel(exportParams, EcCommodityManagementExportVo.class, ecCommodityManagementList); //合併單元格new CellRangeAddress(從第幾行開始, 到第幾行結束, 從第幾列開始, 到第幾列結束) CellRangeAddress cellAddresses = new CellRangeAddress(1, 1, 0, 1); workbook.getSheetAt(0).addMergedRegion(cellAddresses); //建立匯出檔名 String fileName = "商品列表.xlsx"; if (workbook != null){ //讓瀏覽器看的懂我們要幹啥 response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type","application/vnd.ms-excel"); response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8")); workbook.write(response.getOutputStream()); } }
注:持久層程式碼就不貼了
-
編寫匯入使用的Javabean,根據具體的需求來定。
//匯入實體類的唯一標識 @ExcelTarget("uploadExcel") //提供get、set @Data //實現序列化 public class UploadExcelVo implements Serializable { //name 對應匯入的Excel中的列名,必須一致! @Excel(name = "題目") private String topic; @Excel(name = "選項A") private String optionA; @Excel(name = "選項B") private String optionB; @Excel(name = "選項C") private String optionC; @Excel(name = "選項D") private String optionD; @Excel(name = "正確答案(多個答案逗號隔開且必須大寫)") private String rightAnswers; }
-
編寫匯入控制層程式碼
@ApiOperation(value = "題目模板匯入" , notes = "題目模板匯入") @PostMapping("uploadExcel") @ResponseBody public ResultBody uploadExcel(HttpServletRequest request,MultipartFile file){ return sybQuestionBankService.uploadExcel(request,file); }
-
編寫匯入業務層程式碼
`/** * 題目模板匯入 * @param file * @return */ @Override public ResultBody uploadExcel(HttpServletRequest request,MultipartFile file) { //匯入資料總條數 int totalNum = 0; //匯入成功條數 int cg = 0; try { String bankId = request.getParameter("bankId"); //建立資料匯入規則物件 ImportParams importParams = new ImportParams(); //設定第一行為表頭不讀取 importParams.setHeadRows(1); //驗證Excel importParams.setNeedVerify(true); //工具類進行讀取直接封裝返回值型別UploadExcelVo ExcelImportResult<UploadExcelVo> objectExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), UploadExcelVo.class, importParams); //遍歷讀取到的資料 if (objectExcelImportResult.getList() != null && objectExcelImportResult.getList().size() > 0){ totalNum = objectExcelImportResult.getList().size(); SybQuestionBankDetail byQuestionBankIdLimitOne = sybQuestionBankDetailDao.findByQuestionBankIdLimitOne(bankId); int detailSort = 0; if (byQuestionBankIdLimitOne != null && !byQuestionBankIdLimitOne.equals("")){ detailSort = byQuestionBankIdLimitOne.getDetailSort()+1; }else { detailSort = 1; } for (UploadExcelVo uploadExcelVo : objectExcelImportResult.getList()) { //建立題目物件進行儲存資料 SybQuestionBankDetail sybQuestionBankDetail = new SybQuestionBankDetail(); sybQuestionBankDetail.setId(UUIDGenerator.getUUID()); sybQuestionBankDetail.setIsDelete(0); sybQuestionBankDetail.setTopic(uploadExcelVo.getTopic()); sybQuestionBankDetail.setQuestionBankId(bankId); sybQuestionBankDetail.setDetailSort(detailSort); sybQuestionBankDetail.setCreateTime(new Date()); //封裝題目選項 List<Map<String,Object>> options = new ArrayList<>(); Map<String,Object> mapA = new HashMap<>(); mapA.put("optionKey","A"); mapA.put("optionValue",uploadExcelVo.getOptionA()); options.add(mapA); Map<String,Object> mapB = new HashMap<>(); mapB.put("optionKey","B"); mapB.put("optionValue",uploadExcelVo.getOptionB()); options.add(mapB); if (uploadExcelVo.getOptionC() != null && !uploadExcelVo.getOptionC().equals("")){ Map<String,Object> mapC = new HashMap<>(); mapC.put("optionKey","C"); mapC.put("optionValue",uploadExcelVo.getOptionC()); options.add(mapC); } if (uploadExcelVo.getOptionD() != null && !uploadExcelVo.getOptionD().equals("")){ Map<String,Object> mapD = new HashMap<>(); mapD.put("optionKey","D"); mapD.put("optionValue",uploadExcelVo.getOptionD()); options.add(mapD); } sybQuestionBankDetail.setOptions(JSON.toJSONString(options)); //封裝正確答案 String[] split = uploadExcelVo.getRightAnswers().split(",", -1); sybQuestionBankDetail.setRightAnswers(JSON.toJSONString(split)); int insert = sybQuestionBankDetailDao.insert(sybQuestionBankDetail); if (insert > 0){ detailSort++; cg++; } } } } catch (Exception e) { e.printStackTrace(); } return ResultBody.ok().data("應匯入"+totalNum+"條題目,匯入成功"+cg+"條"); }
注:持久層程式碼就不貼了
以上就是easypoi的匯入匯出的使用。