简单EXCEL列表导出

简单EXCEL列表导出_第1张图片
5656.png

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

        
            org.apache.poi
            poi
            3.14
        
        
            org.apache.poi
            poi-ooxml
            3.14
        

工具类:

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> 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 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");

你可能感兴趣的:(简单EXCEL列表导出)