目录
java导出excel
/  

java导出excel

结果如图所示

image.png

image.png

@RequestMapping("/download")
    public void download (Integer year, Integer month, HttpServletResponse response, HttpServletRequest request) throws IOException {
        if (year != 0 && month != 0) {
            List<ProductList> productLists = adminProductService.saleProductRecord(year, month);
            String filename = year + "年" + month + "月销售榜单.xls";
            String sheetName = month + "月销售榜单";
            String titleName = year + "年" + month + "月销售榜单";
            String[] columnName = {"商品名称", "商品销量"};
            String[][] dataList = new String[productLists.size()][2];
            for (int i = 0; i < productLists.size(); i++) {
                dataList[i][0] = productLists.get(i).getName();
                dataList[i][1] = productLists.get(i).getSaleNum().toString();
            }

            // 创建Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 创建excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
            // 设置列宽
            sheet.setDefaultColumnWidth(15);
            // 设置行高 short 类型 行高为18时,则需要设置为 18 * 20
            sheet.setDefaultRowHeight((short)360);
            // 创建sheet的第一行
            HSSFRow row = sheet.createRow(0);
            // 创建第一行的第一个单元格
            HSSFCell cell = row.createCell(0);
            // 合并第一行的两个单元格 第0行,第0列 和 第0行, 第1列 合并
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
            // 给第一行的第一个合并后的单元格赋值
            cell.setCellValue(titleName);
            // 创建第二行
            HSSFRow row1 = sheet.createRow(1);
            /*设置表格样式*/
            HSSFCellStyle cellStyle=wb.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
            cell.setCellStyle(cellStyle);
            row.setRowStyle(cellStyle);
            for (int i = 0; i < 2; i++) {
                HSSFCell cell1 = row1.createCell(i);
                cell1.setCellValue(columnName[i]);
                cell1.setCellStyle(cellStyle);
            }
            row1.setRowStyle(cellStyle);
            // 创建数据行
            for (int i = 0; i < dataList.length; i++) {
                row1 = sheet.createRow(i + 2);
                for (int j = 0; j < 2; j++) {
                    HSSFCell cell1 = row1.createCell(j);
                    cell1.setCellValue(dataList[i][j]);
                    cell1.setCellStyle(cellStyle);
                }
            }
            row1.setRowStyle(cellStyle);

            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("content-Disposition", "attachment;filename=" + processFileName(request, filename));
            OutputStream out = response.getOutputStream();
            // 将wb 写入 到输出流
            wb.write(out);

        }
    }

标题:java导出excel
作者:gitsilence
地址:http://blog.lacknb.cn/articles/2020/05/25/1590403875904.html