POI导出Excel并下载

首先在pom.xml添加jar包:

<!-- 导出excel -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.9</version>
    </dependency>

 导出Excel工具类:

public class ExcelUtil {
    @SuppressWarnings("deprecation")
    public static void excelUtil(HttpServletResponse response,String[] headers,
            List<InsuranceDetailsVO> InsuranceDetailsVOs) 
            throws IOException{
        //创建HSSFWorkbook对象(excel的文档对象)  
        HSSFWorkbook wb = new HSSFWorkbook();  
        //建立新的sheet对象(excel的表单)  
        HSSFSheet sheet = wb.createSheet("CSRExport"); 
        
        //设置列宽
        sheet.setColumnWidth(0, 20*256);
        sheet.setColumnWidth(1, 25*256);
        sheet.setColumnWidth(2, 24*256);
        .....//生成一个样式
        HSSFCellStyle style1 = wb.createCellStyle();
        
        //字体设置
        HSSFFont font = wb.createFont();    
        font.setFontName("仿宋_GB2312");    
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示    
        font.setFontHeightInPoints((short) 12);
        
//        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style1.setAlignment(CellStyle.ALIGN_CENTER);//水平居中  
        style1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
        style1.setFont(font);
        style1.setWrapText(true);
        
        HSSFRow row1=sheet.createRow(0);  
        
        for (short i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]);
            row1.getCell(i).setCellStyle(style1);
        }
        for (int i = 0; i < InsuranceDetailsVOs.size(); i++) {
            HSSFRow row=sheet.createRow(i+1);
            ....这里是给每一行的每一列填充值
        }
        
        String fileName = "default.xls";
        try {
            fileName = "LD"+DateFormatUtils.getSystemDateByYYYYMMDD()+".xls";
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        
        //输出流
        OutputStream os=null;
        try {
             response.reset();
             response.setCharacterEncoding("UTF-8");
             response.setHeader("Content-Disposition", "attachment; filename="+fileName);
//             response.setContentType("application/vnd.ms-excel;charset=utf-8"); 
             response.setContentType("application/octet-stream;charset=UTF-8");  //流输出
             os = new BufferedOutputStream(response.getOutputStream());
             wb.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    
}

 

posted @ 2016-12-28 17:52  编码龟  阅读(414)  评论(0编辑  收藏  举报