spring boot导出excel

    博主第一次导出,踩了很多坑,最坑的是,本地能导出,但是一旦上传服务器就over了,没办法,只能换,参考了其他的博客,避免一些问题,共学习吧。话不多说,直接上代码。(博主用的是谷歌浏览器)

     1.首先是controller层

     @ResponseBody 

     @GetMapping("/Excel")

    R Excel(HttpServletRequest request, HttpServletResponse response,@RequestParam Map params) throws Exception {   //按照你项目的实际需要,根据什么条件导出,就传什么参数

         List waybills = waybillService.list(params);  

        Export.main(request, response, waybills);
        return “成功 ”;   

}

 

2.公用类Export

@SuppressWarnings({ "deprecation" })

public class Export {
    
    public static void main(HttpServletRequest request, HttpServletResponse response, List dataList) throws Exception {

        String sheetName = "运单数据";
        String titleName = "运单数据";
        String fileName = "运单数据";
        int columnNumber = 3;
        int[] columnWidth = { 10, 10, 10 };
        String[] columnName = { "序号", "运单号", "运单"};
        new Export().exportWithResponse(sheetName, titleName, fileName, columnNumber, columnWidth, columnName, dataList, response);
    }

public void exportWithResponse(String sheetName, String titleName, String fileName, int columnNumber,
            int[] columnWidth, String[] columnName, List dataList,HttpServletResponse response)
            throws Exception {

        if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
            // 第一步,创建一个webbook,对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
            //统一设置列宽
            // sheet.setDefaultColumnWidth(15); 
            for (int i = 0; i < columnNumber; i++) {
                for (int j = 0; j <= i; j++) {
                    if (i == j) {
                        // 单独设置每列的宽
                        sheet.setColumnWidth(i, columnWidth[j] * 256); 
                    }
                }
            }
            // 创建第0行 也就是标题
            HSSFRow row1 = sheet.createRow((int) 0);
            // 设备标题的高度
            row1.setHeightInPoints(30);
            // 第三步创建标题的单元格样式style2以及字体样式headerFont1
            HSSFCellStyle style2 = wb.createCellStyle();
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            // 创建字体样式
            HSSFFont headerFont1 = (HSSFFont) wb.createFont();
            // 字体加粗
            headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 设置字体类型
            headerFont1.setFontName("黑体");
            // 设置字体大小
            headerFont1.setFontHeightInPoints((short) 15);
            // 为标题样式设置字体样式
            style2.setFont(headerFont1);
            // 创建标题第一列
            HSSFCell cell1 = row1.createCell(0);
            // 合并列标题
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1));
            // 设置值标题
            cell1.setCellValue(titleName);
            // 设置标题样式
            cell1.setCellStyle(style2);

            // 创建第1行 也就是表头
            HSSFRow row = sheet.createRow((int) 1);
            // 设置表头高度
            row.setHeightInPoints(27);

            // 第四步,创建表头单元格样式 以及表头的字体样式
            HSSFCellStyle style = wb.createCellStyle();
            // 设置自动换行
            style.setWrapText(true);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 创建一个居中格式
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

            style.setBottomBorderColor(HSSFColor.BLACK.index);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            // 创建字体样式
            HSSFFont headerFont = (HSSFFont) wb.createFont();
            // 字体加粗
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 设置字体类型
            headerFont.setFontName("黑体");
            // 设置字体大小
            headerFont.setFontHeightInPoints((short) 10);
            // 为标题样式设置字体样式
            style.setFont(headerFont);

            // 第四.一步,创建表头的列
            for (int i = 0; i < columnNumber; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(columnName[i]);
                cell.setCellStyle(style);
            }

            // 第五步,创建单元格,并设置值
            
            (特别注意,这个设置格式的要放在数据循环的外面,不然导出以后,office打开,只有20行有格式,这个问题当时困扰了博主很久,具体原因我不是很能解释清楚,不多说了,你们注意即可)
            // 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
            HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
            // 设置自动换行
            zidonghuanhang2.setWrapText(true);
            // 创建一个上下居中格式
            zidonghuanhang2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            // 左右居中
            zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            // 设置边框
            zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
            zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);       

    
            
             // 插入数据的数据ROW
            int lastRow = sheet.getLastRowNum() + 1;
            for (int i = 0; i < dataList.size(); i++) {

            // 创建新的ROW,用于数据插入
                row = sheet.createRow(lastRow + i);
                // row = sheet.createRow((int) i + 2);
                // 为数据内容设置特点新单元格样式1 自动换行 上下居中
                HSSFCellStyle zidonghuanhang = wb.createCellStyle();
                // 设置自动换行
                zidonghuanhang.setWrapText(true);
                // 创建一个居中格式
                zidonghuanhang.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

                // 设置边框
                zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
                zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
                zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);

                HSSFCell datacell = null;
                // 按项目实际需求,在该处将对象数据插入到Excel中
                Waybill wl = dataList.get(i);
                if (null == wl) {
                    break;
                }
                // Cell赋值开始(每行数据的序号)
                datacell = row.createCell(0);
                datacell.setCellValue(i+1);
                datacell.setCellStyle(zidonghuanhang2);

                // cell赋值开始
                if (wl.getWaybillNo() != null) {
                    datacell = row.createCell(1);
                    datacell.setCellValue(wl.getWaybillNo());
                    datacell.setCellStyle(zidonghuanhang2);
                }else {
                    datacell = row.createCell(1);
                    datacell.setCellValue("-");
                    datacell.setCellStyle(zidonghuanhang2);
                }

 

                if (wl.getWaybillNo() != null) {
                    datacell = row.createCell(2);
                    datacell.setCellValue(wl.getWaybillNo());
                    datacell.setCellStyle(zidonghuanhang2);
                }else {
                    datacell = row.createCell(2);
                    datacell.setCellValue("-");
                    datacell.setCellStyle(zidonghuanhang2);
                }

            // 第六步,将文件存到浏览器设置的下载位置
            String filename = fileName + ".xls";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=".concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
            OutputStream out = response.getOutputStream();
            try {
                // 将数据写出去
                wb.write(out);
                String str = "导出" + fileName + "成功!";
                System.out.println(str);
            } catch (Exception e) {
                e.printStackTrace();
                String str1 = "导出" + fileName + "失败!";
                System.out.println(str1);
            } finally {
                out.close();
            }

        } else {
            System.out.println("列数目长度名称三个数组长度要一致");
        }

    }
}

你可能感兴趣的:(spring boot导出excel)