下载上传Excel

                                                              下载excel需要几步

1.在controller中

    @RequestMapping("download.html")
    public void download(HttpServletRequest request,HttpServletResponse response){
        try {
            doDoenload(request,response);
        } catch (IOException e) {
            log.error("下载模板失败:",e);
        }
    }

    private void doDoenload(HttpServletRequest request,HttpServletResponse response) throws IOException{
        response.reset();

        OutputStream  outStream = response.getOutputStream();
        String[] excelHeads = UploadConstant.setHead(request);
        response.setHeader("Content-disposition",
                "attachment; filename="+new          String((UploadConstant.setExcelName(request)+".xls").getBytes("UTF-8"),"ISO_8859_1"));
        response.setContentType("application/msexcel");
       
        @SuppressWarnings("resource")
        HSSFWorkbook wb = new HSSFWorkbook();


        //创建sheet
        String excelSheetName = UploadConstant.setSheetName(request);
        HSSFSheet sheet = wb.createSheet(excelSheetName);                                    //设置sheet名称
        HSSFCellStyle style = wb.createCellStyle();                                            //创建Excel样式
        style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);                               
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);                                        //居中
        style.setWrapText(true);                                                            //自动换行
       
        //设置第一行数值
        String excelNote = UploadConstant.setNote(request);
        HSSFRow firstRow = sheet.createRow((int) 0);                                        //创建第一行
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, excelHeads.length - 1));        //第一行列合并
        HSSFCell friCell = firstRow.createCell(0);
        friCell.setCellValue(excelNote);
        friCell.setCellStyle(style);
       
        //设置第二行数值
        HSSFRow secondRow = sheet.createRow((int) 1);                                        //创建第二行
        for (int i = 0; i < excelHeads.length; i++) {                                        //设置第二行表头
            HSSFCell cell = secondRow.createCell(i);
            cell.setCellValue("                "+excelHeads[i]+"                ");
            cell.setCellStyle(style);
            sheet.autoSizeColumn(i);
        }
       
        wb.write(ouputStream);
       
        ouputStream.flush();
        ouputStream.close();

};

猜你喜欢

转载自zhangwenjun828.iteye.com/blog/2248972