JavaWeb中使用poi进行excel的自定义模板下载

版权声明:本文为博主原创文章,转载请注明原帖地址,谢谢 https://blog.csdn.net/AooMiao/article/details/81455302

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
这篇文章我以读写excel2003为例,若想操作2007以及上的excel,请使用poi-ooxml

1.先添加jar包依赖

<dependency><!-- excel2003 -->
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>5
</dependency>
<dependency><!-- excel2007以上 -->
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.8</version>
</dependency>

2.代码编写

public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{
    String title[] = new String[]{"标题1", "标题2", "标题3"};//excel第一行标题内容
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("导入模板");//工作薄名称 
    sheet.setDefaultColumnWidth(18);//列宽

    // 樣式
    HSSFCellStyle headStyle = workbook.createCellStyle();
    headStyle.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
    headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
    headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); // 垂直居中
    headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
    headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
    headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
    headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
    HSSFDataFormat format = workbook.createDataFormat();  
    headStyle.setDataFormat(format.getFormat("@"));  //设置单元格格式为常规
    //设置头格式(第一行)
    HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
    columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
    columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
    columnHeadStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
    columnHeadStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
    columnHeadStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框

    int rowNO = 0;
    HSSFRow row = null;
    HSSFCell cell = null;
    row = sheet.createRow(rowNO++);
    row.setHeight((short) 400);
    //两个for循环,生成execl的标题
    for (int i = 0; i < title.length; i++) {
        cell = row.createCell(i);
        cell.setCellValue(title[i]);
        cell.setCellStyle(headStyle);
    }

    String fileName = "导入模板.xls";//excel文件名
    response.setContentType("application/download;charset=UTF-8");//告诉浏览器返回文件下载
    response.setHeader("Content-disposition", "attachment;filename=\""
            + new String(fileName.getBytes("UTF-8"), "ISO8859_1") + "\"");//激活文件下载保存框
    OutputStream out = response.getOutputStream();
    workbook.write(out);
    out.close();
}

总结:HSSFWorkbook某种意义上就是一个代码中的excel,我们对它的操作就是对excel的操作,createCellStyle()方法返回单元格的样式设计入口,关于其他excel的操作在api文档会有很多的解释,API网址


猜你喜欢

转载自blog.csdn.net/AooMiao/article/details/81455302