我是靠谱客的博主 文艺自行车,最近开发中收集的这篇文章主要介绍记录一次复杂的Excel导出(三),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

上篇生成复杂Excel并合并多sheet表格:https://blog.csdn.net/BinshaoNo_1/article/details/114981610

这篇记录一下,下载和相关的数据类型

一,下载

/**
     * 下载多sheet模板
     * @param response
     */
    public void downloadExcelByManySheet(HttpServletResponse response,String url,String filename,String[] sheetNameArray,Integer[] integers) {
        TemplateExportParams params = new TemplateExportParams(url);
        Map<String, Object> map = new HashMap<String, Object>();
        //固定sheet下载
//        String[] sheetNameArray = {"sheetName1","sheetName2"} ;
//        Integer[] integers = {1,2} ;

        params.setScanAllsheet(true);
        //不固定sheet
        params.setSheetName(sheetNameArray);
        params.setSheetNum(integers);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        response.setContentType("application/x-msdownload");// 下载设置
        response.setHeader("Content-Disposition",
                "attachment;filename=" + this.genAttachmentFileName(filename,"导出.xls"));// 下载设置
        try{
            OutputStream ous = response.getOutputStream();
            workbook.write(ous);
            ous.close();
            workbook.close();
        }catch (Exception e){
            log.error("下载异常:{}",e.getMessage());
        }
    }
    //解决标题乱码
    public String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }

对下载Excel的数据的操作,因为其他需求,需要对下载的表格内容进行操作,但是表格中会出现#VALUE!,出现这样的原因是因为数据字段的问题,所以就操作了一下,由于是从html模板转换而来,有些东西用不了(用于时间原因,没有去证实),所以就用了比较粗糙的方式,这段代码是把html转换的空值""转成空白值导出,可以进行表格计算

/**
     * 读取生成的Excel表,判断为“”的字段转换成空白
     * @param response
     * @param filePath
     * @param fileName
     * @throws IOException
     */
    private void readOperateExcel(HttpServletResponse response,String filePath,String fileName) throws IOException {
        XSSFWorkbook wookbook = new XSSFWorkbook(new FileInputStream(filePath));
        //创建一个新的Excel文档
        XSSFWorkbook newExcelCreat = new XSSFWorkbook();

        XSSFSheet sheetAt = wookbook.getSheetAt(0);

        //获取到Excel文件中的所有行数
        int rows = sheetAt.getPhysicalNumberOfRows();
        //遍历行
        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格
            XSSFRow row = sheetAt.getRow(i);

            if (null != row){
                for (int k = 0,lastSize = row.getLastCellNum();k < lastSize;k++){
                    String xCellFormatValue = getXCellFormatValue(row.getCell(k));
                    if(ToolUtil.isEmpty(xCellFormatValue)){
                        xCellFormatValue = null;
                    }
                    row.getCell(k).setCellValue(xCellFormatValue);
                    
                }
            }
        }
        XSSFSheet newSheet = newExcelCreat.createSheet(sheetAt.getSheetName());
        //方法详见上一篇
        CopyWorkBookUtil.copySheet(newExcelCreat, sheetAt, newSheet);
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        try{
            FileOutputStream fileOut = new FileOutputStream("D:\file\test\" + timeInMillis + ".xlsx");
            newExcelCreat.write(fileOut);
            fileOut.close();
            newExcelCreat.close();
        }catch (Exception e){
            log.error("生成异常:{}",e.getMessage());
        }
        downloadExcel(response, "D:\file\test\" + timeInMillis + ".xlsx", timeInMillis + ".xlsx");
    }
    //这种方式目前只能使用字符串类型,基本不合适这里,放出来只是供参考
    private static String getXCellFormatValue(XSSFCell cell) {
        String cellValue = null;
        if (null != cell) {
            switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_STRING:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                case XSSFCell.CELL_TYPE_NUMERIC:
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                default:
                    cellValue = null;
            }
        } else {
            cellValue = null;
        }
        return cellValue;
    }

未转之前表格:

计算出现""错误,转换之后则没有问题,可以计算。

再附上下载时的转换

 /**
     * 下载模板
     * @param response
     */
    public void downloadExcel(HttpServletResponse response,String url,String filename) {
        TemplateExportParams params = new TemplateExportParams(url);
        Map<String, Object> map = new HashMap<String, Object>();
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        XSSFSheet sheetAt = (XSSFSheet) workbook.getSheetAt(0);

        //获取到Excel文件中的所有行数
        int rows = sheetAt.getPhysicalNumberOfRows();
        //遍历行
        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格
            XSSFRow row = sheetAt.getRow(i);
            if (null != row){
                for (int k = 0,lastSize = row.getLastCellNum();k < lastSize;k++){
                    String xCellFormatValue = null;
                    XSSFCell cell = row.getCell(k);
                    //方法同上,未优化
                    xCellFormatValue = getXCellFormatValue(cell);
                    int cellType = cell.getCellType();
                    if (ToolUtil.isNotEmpty(xCellFormatValue)){
                        //方法未生效用正则判断数字为数值
                        if (isMatch(matchs,xCellFormatValue)) {
                            row.getCell(k).setCellValue(Double.valueOf(cell.getRichStringCellValue().toString()));
                        }else if(cellType == XSSFCell.CELL_TYPE_STRING){
                            row.getCell(k).setCellValue(cell.getRichStringCellValue().getString());
                        }
                    }else {
                        xCellFormatValue = null;
                        row.getCell(k).setCellValue(xCellFormatValue);
                    }


                }
            }
        }


        response.setContentType("application/x-msdownload");// 下载设置
        response.setHeader("Content-Disposition",
                "attachment;filename=" + this.genAttachmentFileName(filename,"导出.xls"));// 下载设置
        try{
            OutputStream ous = response.getOutputStream();
            workbook.write(ous);
            ous.close();
            workbook.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
private String matchs = "[0-9.]+";
private static boolean isMatch(String regex, String orginal){
        if (orginal == null || orginal.trim().equals("")) {
            return false;

        }

        Pattern pattern = Pattern.compile(regex);

        Matcher isNum = pattern.matcher(orginal);

        return isNum.matches();

    }
    public String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }

 

到此结束!

 

 

 

 

最后

以上就是文艺自行车为你收集整理的记录一次复杂的Excel导出(三)的全部内容,希望文章能够帮你解决记录一次复杂的Excel导出(三)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部