java操作poi生成excel.xlsx(設置下拉框)下載本地和前端下載


需求:導入excel表格,如果excel有錯誤,將錯誤的地方標紅,在把數據以excel的形式寫出,供用戶下載
解決方案:1.以實體類的方式接收excel並解析(創建兩個集合一個接收正常的數據一個接收錯誤的數據)
2.錯誤集合無論正確錯誤數據都要存儲,並記錄是否有誤(錯誤數據拼接特殊字符作為標記,然后記錄寫入集合)
3.如果發現記錄有錯誤記錄,就要使用錯誤數據集合生成excel(對錯誤的數據對特殊字符截取)
4.將錯誤的excel生成到工程的相對的路徑下,也可以上傳服務器更好(下次下載前要記得清理記錄),返回前端一個地址,前端點擊鏈接進行下載
5.下面是片段代碼

  public static SXSSFWorkbook createExportInterviewExcel(List<Operator> data, String sheetName) {
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(100);
        //標題欄設置
        CellStyle style = sxssfWorkbook.createCellStyle();
        style.setWrapText(true);//自動換行
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居左
        Font font = sxssfWorkbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);         //字體增粗
        style.setFont(font);
        DataFormat formats = sxssfWorkbook.createDataFormat();
        style.setDataFormat(formats.getFormat("@"));//設置文本格式

        //正常格式設置
        CellStyle cellStyle = sxssfWorkbook.createCellStyle();
        //cellStyle.setWrapText(true);//自動換行
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居左
        DataFormat format = sxssfWorkbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("@"));//設置文本格式

        Sheet taskInfoSheet = sxssfWorkbook.createSheet(sheetName);
        DataValidationHelper helper = taskInfoSheet.getDataValidationHelper();//設置下拉框xlsx格式
//設置列寬
        taskInfoSheet.setColumnWidth(5, 256 * 21);
        taskInfoSheet.setColumnWidth(6, 256 * 15);
        taskInfoSheet.setColumnWidth(7, 256 * 15);
        taskInfoSheet.setColumnWidth(8, 256 * 20);
        taskInfoSheet.setColumnWidth(18, 256 * 20);
        // 第一行標題
        Row row_tital = taskInfoSheet.createRow(0);

        String[] keyWord = {"姓名","性別","民族", "年齡", "學歷", "身份證號", "手機號",
                "在我司任職過", "崗位名", "廣告名", "部門","工作地", "推薦人","推薦人電話","推薦人部門","推薦人工號", "面試安排時間","是否錄用", "淘汰類型", "淘汰原因"};
        for (int i = 0; i < keyWord.length; i++) {
            Cell cell_tital_index = row_tital.createCell(i);
            cell_tital_index.setCellValue(keyWord[i]);
            cell_tital_index.setCellStyle(style);
        }

        //異常情況處理
        if (CollectionUtils.isEmpty(data) ||(CollectionUtils.isNotEmpty(data) && StringUtils.isBlank(data.get(0).getName()))) {
            return sxssfWorkbook;
        }

        // 數據行
        for (int i = 0; i < data.size(); i++) {  // 導出詳情
            Row row_data = taskInfoSheet.createRow(i + 1);
            Cell cell_data_name = row_data.createCell(0);
            cell_data_name.setCellValue(data.get(i).getName());
            cell_data_name.setCellStyle(cellStyle);


            Cell cell_data_nation = row_data.createCell(1);
            cell_data_nation.setCellValue(data.get(i).getNational());
            cell_data_nation.setCellStyle(cellStyle);

            Cell cell_data_age = row_data.createCell(2);

            Integer age= null;
            if(data.get(i).getAge()!= null){
                 age = data.get(i).getAge();
            }else{
                age=1;
            }
            cell_data_age.setCellValue(age);
            cell_data_age.setCellStyle(cellStyle);


            
            //添加工作地
            Cell cell_data_location =row_data.createCell(3);
            cell_data_location.setCellValue(data.get(i).getLocation());
            cell_data_location.setCellStyle(cellStyle);

            Cell cell_data_referrer = row_data.createCell(4);
            cell_data_referrer.setCellValue(data.get(i).getReferrer());
            cell_data_referrer.setCellStyle(cellStyle);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String interviewTime = "";
            if (null != data.get(i).getInterviewTime()) {
                interviewTime = sdf.format(data.get(i).getInterviewTime());
            }
            Cell cell_data_interviewTime = row_data.createCell(5);
            cell_data_interviewTime.setCellValue(interviewTime);
            cell_data_interviewTime.setCellStyle(cellStyle);

            String[] yesOrNo = {"是", "否"};
            creatDropDownList(taskInfoSheet,helper,yesOrNo,1,200,6,6);

            String[] list = {"不符合返聘要求", "不符合公司規則", "綜合素質", "其他"};
            creatDropDownList(taskInfoSheet, helper, list, 1, 200, 7, 7);
        }

        return sxssfWorkbook;
    }

    //創建下拉框
    private static void creatDropDownList(Sheet taskInfoSheet, DataValidationHelper helper, String[] list,
                                     Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol) {
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        //設置下拉框數據
        DataValidationConstraint constraint = helper.createExplicitListConstraint(list);
        DataValidation dataValidation = helper.createValidation(constraint, addressList);
        //處理Excel兼容性問題
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        taskInfoSheet.addValidationData(dataValidation);
    }

//需求:導入excel表格,如果excel有錯誤,將錯誤的地方標紅,在把數據以excel的形式寫出,供用戶下載
//解決方案:1.以實體類的方式接收excel並解析(創建兩個集合一個接收正常的數據一個接收錯誤的數據)
//2.錯誤集合無論正確錯誤數據都要存儲,並記錄是否有誤(錯誤數據拼接特殊字符作為標記,然后記錄寫入集合)
//3.如果發現記錄有錯誤記錄,就要使用錯誤數據集合生成excel(對錯誤的數據對特殊字符截取)
//4.將錯誤的excel生成到工程的相對的路徑下(下次下載前要記得清理記錄),返回前端一個地址,前端點擊鏈接進行下載

//這個方法就是清除之前的文件夾
 private String getExportResult(SXSSFWorkbook sxssfWorkbook) {

        //刪除之前文件夾下的文件
        String targetUrl = System.getProperty("export.error.result");
        File targetFile = new File(targetUrl);
        ContentUtil.deletAllFiles(targetFile);

        String fileName = null;
        try {
            fileName = System.getProperty("export.error.result") + UUID.randomUUID().toString() + ".xlsx";
            File file = new File(fileName);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream outputStream = new FileOutputStream(fileName);
            sxssfWorkbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            logger.error("OperatorInfoImportAuditResultServiceImpl下載導入錯誤excel表格異常", e);
            e.printStackTrace();
        }
        return fileName;
    }
 public static void deletAllFiles(File file) {
        if (file == null) {
            return;
        }
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            }else if (file.isDirectory()) {
                File[] listFiles = file.listFiles();
                if (listFiles == null) {
                    return;
                }
                for (File file2 : listFiles) {
                    deletAllFiles(file2);
                }
               /* //遞歸跳出來的時候刪除空文件夾
                file.delete();*/
            }
        }
    }

@RequestMapping(value = "/exportErrorImportResult", method = RequestMethod.GET)
    public void exportErrorImportResult(@RequestParam(value = "paramUrl") String paramUrl, HttpServletResponse response, HttpServletRequest request) {

        //生成錯誤的文檔
        try {
            XSSFWorkbook workbook = null;
            File file = new File(paramUrl);
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                workbook = new XSSFWorkbook(in);
            } else {
                logger.info("初級員工內推導出錯誤的excel文件,文件不存在");
            }
            OutputStream ouputStream = response.getOutputStream();
            String fileName = "導出錯誤";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();

        } catch (Exception e) {
            logger.error("導出錯誤的excel文件,OperatorPostInfoController 異常:", e);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM