创建多样化Excel表头

package cn.wizzer.app.web.commons.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Ted {
    private Log log= Logs.get();

    /**
     *  导出excel (HSSFWorkbook)
     */
    public void exportExcel() {

        /** 第一步,创建一个Workbook,对应一个Excel文件  */
        HSSFWorkbook wb = new HSSFWorkbook();

        /** 第二步,在Workbook中添加一个sheet,对应Excel文件中的sheet  */
        HSSFSheet sheet = wb.createSheet("excel导出标题");

        /** 第三步,设置样式以及字体样式*/
        HSSFCellStyle titleStyle = createTitleCellStyle(wb);
        HSSFCellStyle headerStyle = createHeadCellStyle(wb);
        HSSFCellStyle contentStyle = createContentCellStyle(wb);

        /** 第四步,创建标题 ,合并标题单元格 */
        // 行号
        int rowNum = 0;
        // 创建第一页的第一行,索引从0开始
        HSSFRow row0 = sheet.createRow(rowNum++);
        log.info("创建第一页的第"+(rowNum++)+"行");
        row0.setHeight((short) 800);// 设置行高

        String title = "excel导出标题";
        HSSFCell c00 = row0.createCell(0);
        c00.setCellValue(title);
        c00.setCellStyle(titleStyle);
        // 合并单元格,参数依次为起始行,结束行,起始列,结束列 (索引0开始)
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));//标题合并单元格操作,6为总列数

        // 第二行
        HSSFRow row1 = sheet.createRow(rowNum++);
        log.info("创建第一页的第"+(rowNum++)+"行");
        row1.setHeight((short) 500);
        String[] row_first = {"填表单位:", "", "", "", "", " 2019年第2季度 ", ""};
        for (int i = 0; i < row_first.length; i++) {
            HSSFCell tempCell = row1.createCell(i);
            tempCell.setCellStyle(headerStyle);
            if (i == 0) {
                tempCell.setCellValue(row_first[i] + "测试单位");
            } else if (i == 5) {
                tempCell.setCellStyle(headerStyle);
                tempCell.setCellValue(row_first[i]);
            } else {
                tempCell.setCellValue(row_first[i]);
            }
        }

        // 合并
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));

        //第三行
        HSSFRow row2 = sheet.createRow(rowNum++);
        row2.setHeight((short) 700);
        String[] row_second = {"名称", "采集情况", "", "", "登记情况", "", "备注"};
        for (int i = 0; i < row_second.length; i++) {
            HSSFCell tempCell = row2.createCell(i);
            tempCell.setCellValue(row_second[i]);
            tempCell.setCellStyle(headerStyle);
        }


        // 合并
        sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));//名称
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 3));//人数情况
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 5));//登记情况
        sheet.addMergedRegion(new CellRangeAddress(2, 3, 6, 6));//备注

        //第三行
        HSSFRow row3 = sheet.createRow(rowNum++);
        row3.setHeight((short) 700);
        String[] row_third = {"", "登记数(人)", "办证总数(人)", "办证率(%)", "登记户数(户)", "签订数(份)", ""};
        for (int i = 0; i < row_third.length; i++) {
            HSSFCell tempCell = row3.createCell(i);
            tempCell.setCellValue(row_third[i]);
            tempCell.setCellStyle(headerStyle);
        }

        //循环每一行数据
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(); //查询出来的数据
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name", "测试名称1");
        map.put("r1", "111");
        map.put("r2", "222");
        map.put("r3", "333");
        map.put("r4", "444");
        map.put("r5", "555");
        map.put("r6", "666");
        dataList.add(map);
        dataList.add(map);//加多一条list

        for (Map<String, Object> excelData : dataList) {
            HSSFRow tempRow = sheet.createRow(rowNum++);
            tempRow.setHeight((short) 500);
            // 循环单元格填入数据
            for (int j = 0; j < 7; j++) {
                HSSFCell tempCell = tempRow.createCell(j);
                tempCell.setCellStyle(contentStyle);
                String tempValue;
                if (j == 0) {
                    // 乡镇、街道名称
                    tempValue = excelData.get("name").toString();
                } else if (j == 1) {
                    // 登记数(人)
                    tempValue = excelData.get("r1").toString();
                } else if (j == 2) {
                    // 办证总数(人)
                    tempValue = excelData.get("r2").toString();
                } else if (j == 3) {
                    // 办证率(%)
                    tempValue = excelData.get("r3").toString();
                } else if (j == 4) {
                    // 登记户数(户)
                    tempValue = excelData.get("r4").toString();
                } else if (j == 5) {
                    // 签订数(份)
                    tempValue = excelData.get("r5").toString();
                } else {
                    // 备注
                    tempValue = excelData.get("r6").toString();
                }
                tempCell.setCellValue(tempValue);
            }
        }


        // 注释行
        HSSFRow remark = sheet.createRow(rowNum++);
        remark.setHeight((short) 500);
        String[] row_remark = {"注:表中的“办证率=办证总数÷登记数×100%”", "", "", "", "", "", ""};
        for (int i = 0; i < row_remark.length; i++) {
            HSSFCell tempCell = remark.createCell(i);
            if (i == 0) {
                tempCell.setCellStyle(headerStyle);
            } else {
                tempCell.setCellStyle(contentStyle);
            }
            tempCell.setCellValue(row_remark[i]);
        }
        int remarkRowNum = dataList.size() + 4;
        sheet.addMergedRegion(new CellRangeAddress(remarkRowNum, remarkRowNum, 0, 6));//注释行合并单元格

        // 尾行
        HSSFRow foot = sheet.createRow(rowNum++);
        foot.setHeight((short) 500);
        String[] row_foot = {"审核人:", "", "填表人:", "", "填表时间:", "", ""};
        for (int i = 0; i < row_foot.length; i++) {
            HSSFCell tempCell = foot.createCell(i);
            tempCell.setCellStyle(contentStyle);
            if (i == 0) {
                tempCell.setCellValue(row_foot[i] + "张三");
            } else if (i == 2) {
                tempCell.setCellValue(row_foot[i] + "李四");
            } else if (i == 4) {
                tempCell.setCellValue(row_foot[i] + "xxxx");
            } else {
                tempCell.setCellValue(row_foot[i]);
            }
        }
        int footRowNum = dataList.size() + 5;
        // 注
        sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 2, 3));
        sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 4, 6));


        //导出
        //HttpServletResponse response = this.getResponse();
        String fileName = "报表名称.xls";

        try {
           // fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
           // response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
           // OutputStream stream = response.getOutputStream();
           /* if (null != wb && null != stream) {
                wb.write(stream);// 将数据写出去  
                wb.close();
                stream.close();
            }*/
            File file = new File("D:\\test.xlsx");
            if(file.exists()){
                file.delete();
                file.createNewFile();
            }else {
                file.createNewFile();
            }
            wb.write(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        // 生成12号字体
        HSSFFont font = wb.createFont();
        font.setColor((short)8);
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);

        return cellStyle;
    }

    private HSSFCellStyle createHeadCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色
        cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont.setBold(true); //字体加粗
        headerFont.setFontName("黑体"); // 设置字体类型
        headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式

        return cellStyle;
    }

    private HSSFCellStyle createTitleCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色

        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setBold(true); //字体加粗
        headerFont1.setFontName("黑体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式

        return cellStyle;
    }

    public static void main(String[] args) {
        Ted ted = new Ted();
        ted.exportExcel();

    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NPOI是一个流行的.NET库,用于读取、写入和操作Microsoft Office格式文件(如Excel、Word和PowerPoint)。要使用NPOI创建Excel表头,可以按照以下步骤进行操作: 1. 创建一个新的工作簿对象。 ``` HSSFWorkbook workbook = new HSSFWorkbook(); ``` 2. 创建一个新的工作表对象。 ``` ISheet sheet = workbook.CreateSheet("Sheet1"); ``` 3. 创建一个新的行对象。 ``` IRow row = sheet.CreateRow(0); ``` 4. 创建单元格并设置单元格的值。 ``` ICell cell = row.CreateCell(0); cell.SetCellValue("Column1"); cell = row.CreateCell(1); cell.SetCellValue("Column2"); cell = row.CreateCell(2); cell.SetCellValue("Column3"); // 继续创建单元格,以此类推 ``` 5. 设置单元格样式(可选)。 ``` ICellStyle style = workbook.CreateCellStyle(); style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; // 继续设置样式,以此类推 cell.CellStyle = style; ``` 6. 将工作簿写入Excel文件。 ``` using (FileStream file = new FileStream("path/to/file.xls", FileMode.Create, FileAccess.Write)) { workbook.Write(file); } ``` 注意,以上示例使用的是xls格式文件,如果需要创建xlsx格式文件,只需要将HSSFWorkbook更改为XSSFWorkbook。此外,上述示例创建的是一个包含一行表头的工作表。如果需要创建包含多行表头的工作表,只需要创建多个行对象并将它们添加到工作表中即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值