简单EXCEL列表导出

2018-06-06  本文已影响0人  离别刀
5656.png

本例子,简单介绍excel导出功能,基于HttpServletResponse,网络文件下载。
依赖jar

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>

工具类:

public abstract class ExportInterface {

     void write(HttpServletResponse response,Workbook workbook){
         String fileName= UUID.randomUUID().toString()+".xls";
         pwrite(response,workbook,fileName);
     }
    void write(HttpServletResponse response,Workbook workbook,String fileName){
        if(StringUtils.isEmpty(fileName)){
            fileName= UUID.randomUUID().toString()+".xls";
        }
        pwrite(response,workbook,fileName);
    }
    void write(HttpServletResponse response, List<List<String>> lists, String fileName){
        if(StringUtils.isEmpty(fileName)){
            fileName= UUID.randomUUID().toString()+".xls";
        }
        SXSSFWorkbook workbook= new SXSSFWorkbook(lists.size());
        SXSSFSheet sheet = workbook.createSheet(fileName.substring(0,fileName.indexOf(".xls")));
        Integer rowIndex=0;
        Row row=null;
        Cell cell=null;
        for(List<String> rowData:lists){
            Integer columnIndex=0;
            row= sheet.createRow(rowIndex++);
            for (String columnVal:rowData){
                cell= row.createCell(columnIndex++);
                cell.setCellValue(columnVal);
            }
        }
        pwrite(response,workbook,fileName);
    }

    private void pwrite(HttpServletResponse response,Workbook workbook,String fileName){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.addHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            fileName= UUID.randomUUID().toString()+".xls";
            response.addHeader("Content-Disposition", "attachment; filename="+fileName);
        }
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

用法

子类继承上述工具类接口,调用父类方法实现数据写出
write(response, lists, "测试.xls");
上一篇下一篇

猜你喜欢

热点阅读