Java通过HSSFWorkbook实现一张excel生成多个sheet页

//待调用的后端方法
@RequestMapping(value = "/manage/list/export")
@ResponseBody
public void doExportExcel(HttpServletResponse response,HttpServletRequest request,String keyId) {
        OutputStream ouputStream = null;
        try {
            ReturnDO<EXCELVO> rdo = excelService.getEXCELVOById(keyId);
            if (rdo.isSuccess() && StringTool.isNotEmpty(rdo.getObj())) {
                HSSFWorkbook wb = new HSSFWorkbook();
                //第一页sheet表
                exportExcel(wb, 0, "表1",rdo.getObj());
                //第二页sheet表
                exportExcel(wb, 1, "表2",rdo.getObj());
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition",
                        "attachment;filename=excelReport.xls");
                ouputStream = response.getOutputStream();
                wb.write(ouputStream);
                ouputStream.flush();
                ouputStream.close();
            }
        } catch (Exception e) {
            logger.debug("导出异常" + e.getMessage());
            e.printStackTrace();
            try {
                ouputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
}

其中exportExcel(wb, 0, "表1",rdo.getObj()); 就是给每个sheet页赋值的方法

//sheetNum页数,sheetTiTle页标题, ReportVO数据实体类
public void exportExcel(HSSFWorkbook workbook, int sheetNum, String sheetTitle, ReportVO vo) throws Exception {
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetTitle);

        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置背景色
        style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        //设置边框居中
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
//        style.setAlignment(HorizontalAlignment.CENTER);// 文字水平居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中

        // 设置字体
        HSSFFont font = workbook.createFont();
        font.setFontName("仿宋_GB2312");
        font.setColor(HSSFColor.OLIVE_GREEN.index);
        font.setFontHeightInPoints((short) 24);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        //生成一行
        HSSFRow row = sheet.createRow((int) 0);
        row.setHeightInPoints(20);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue(sheetTitle);
        cell.setCellStyle(style);
        for (int i = 1; i < 3; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style);
        }
        sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(0, 1, 0, 2));

        // 设置字体
        // 生成一个样式
        HSSFCellStyle style1 = workbook.createCellStyle();
        // 设置背景色
        style1.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
        style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

        //设置边框
        style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
        HSSFFont font1 = workbook.createFont();
        font1.setFontName("仿宋_GB2312");
        font1.setColor(HSSFColor.BLACK.index);
        font1.setFontHeightInPoints((short) 10);
        font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style1.setFont(font1);
        style1.setWrapText(true);

        //生成一行
        HSSFRow row2 = sheet.createRow((int) 2);
        row.setHeightInPoints(20);
        HSSFCell cell1 = row2.createCell(0);
        cell1.setCellValue("名称");
        cell1.setCellStyle(style1);
        sheet.setColumnWidth(0, 5000);

        cell1 = row2.createCell(1);
        cell1.setCellValue("类型");
        cell1.setCellStyle(style1);
        sheet.setColumnWidth(1, 5000);

        cell1 = row2.createCell(2);
        cell1.setCellValue("时间");
        cell1.setCellStyle(style1);
        sheet.setColumnWidth(2, 5000);

        // 生成一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();

        //设置边框
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

        // 设置字体
        HSSFFont font2 = workbook.createFont();
        font2.setFontName("仿宋_GB2312");
        font2.setColor(HSSFColor.BLACK.index);
        font2.setFontHeightInPoints((short) 10);
//        font5.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        HSSFRow row3 = sheet.createRow((int) 3);
        if(StringTool.isNotEmpty(vo.getList()) &&
                vo.getList().size()>0){
            for(int i=0;i< vo.getList().size();i++){
                ElementStepSchedule bean = vo.getList().get(i);
                row3 = sheet.createRow((int) 3 + i);

                cell1 = row3.createCell(0);
                cell1.setCellValue(bean.getName());
                cell1.setCellStyle(style2);

                cell1 = row3.createCell(1);
                String type= "";
                if (StringTool.isNotEmpty(bean.getType())) {
                    if(bean.getType().equals("1")){
                        type= "TRUE";
                    }else if(bean.getType().equals("2")){
                        type= "FLASE";
                    }
                }
                cell1.setCellValue(type);
                cell1.setCellStyle(style2);

                cell1 = row3.createCell(2);
                cell1.setCellValue(DateUtil.formatDateToString(bean.getTime(), "yyyy-MM-dd HH:mm:ss"));
                cell1.setCellStyle(style2);

             
            }
        }

    }
要在Java中根据模板导出Excel报表并复制模板生成多个Sheet,可以使用Apache POI库。下面是一个简单的示例代码,可以将一个模板文件复制多次,并分别填充不同的数据,生成多个Sheet: ```java import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExcelExporter { public static void main(String[] args) throws IOException { // 加载模板文件 FileInputStream templateFile = new FileInputStream("template.xls"); Workbook templateWorkbook = new HSSFWorkbook(templateFile); // 获取模板中的样式和格式 Sheet templateSheet = templateWorkbook.getSheetAt(0); Row templateRow = templateSheet.getRow(0); Cell templateCell = templateRow.getCell(0); CellStyle templateStyle = templateCell.getCellStyle(); DataFormat templateFormat = templateWorkbook.createDataFormat(); // 模拟数据 List<Map<String, Object>> data = new ArrayList<>(); for (int i = 1; i <= 3; i++) { Map<String, Object> map = new HashMap<>(); map.put("name", "Tom" + i); map.put("age", 20 + i); data.add(map); } // 遍历数据,复制模板并填充数据 for (int i = 0; i < data.size(); i++) { Map<String, Object> map = data.get(i); // 复制模板 Sheet sheet = templateWorkbook.cloneSheet(0); templateWorkbook.setSheetName(templateWorkbook.getSheetIndex(sheet), "Sheet" + (i + 1)); // 填充数据 for (int j = 0; j < sheet.getLastRowNum() + 1; j++) { Row row = sheet.getRow(j); if (row == null) { row = sheet.createRow(j); } for (int k = 0; k < row.getLastCellNum(); k++) { Cell cell = row.getCell(k); if (cell == null) { cell = row.createCell(k); } String value = getValueForCell(cell, map); cell.setCellValue(value); cell.setCellStyle(templateStyle); if (value.matches("\\d+")) { // 如果是数字,设置单元格格式 cell.setCellStyle(getNumericCellStyle(templateWorkbook, templateStyle, templateFormat)); } } } } // 删除模板Sheet templateWorkbook.removeSheetAt(0); // 将工作簿保存到文件 FileOutputStream fileOut = new FileOutputStream("workbook.xls"); templateWorkbook.write(fileOut); fileOut.close(); System.out.println("Excel文件导出成功!"); } // 获取单元格的值 private static String getValueForCell(Cell cell, Map<String, Object> map) { String value = ""; if (cell.getCellType() == CellType.STRING) { value = cell.getStringCellValue(); if (value.startsWith("$")) { // 如果是占位符,替换为数据 value = map.get(value.substring(1)).toString(); } } return value; } // 获取数字类型单元格的样式 private static CellStyle getNumericCellStyle(Workbook workbook, CellStyle style, DataFormat format) { CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(style); newStyle.setDataFormat(format.getFormat("#,##0.00")); return newStyle; } } ``` 以上代码中,我们首先加载一个模板文件,并获取其中的样式和格式。接下来,我们模拟了一个数据集,然后遍历数据集,复制模板并填充数据,生成多个Sheet。在填充数据时,我们首先遍历每个单元格,判断其是否为占位符,如果是,则替换为对应的数据。接着,我们将单元格的值设置为填充后的数据,并设置单元格的样式和格式。最后,我们删除了模板Sheet,并将工作簿保存到文件中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值