spring MVC 生成並下載Excel

1、Controller類:

@Controller
@RequestMapping("down")
public class down {
    @RequestMapping(params = "downExcel")
    public String download(HttpServletRequest request,HttpServletResponse response) throws IOException{
    String columnNames[]={"ID","項目名","銷售人","負責人","所用技術","備註"};//列名
    //生成一個Excel文件
    // 創建excel工作簿
    Workbook wb = new HSSFWorkbook();
    // 創建第一個sheet(頁),並命名
    Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
    // 手動設置列寬。第一個參數表示要爲第幾列設;,第二個參數表示列的寬度,n爲列高的像素數。
    for(int i=0;i<keys.length;i++){
        sheet.setColumnWidth((short) i, (short) (35.7 * 150));
    }
    // 創建第一行
    Row row = sheet.createRow((short) 0);
    //設置列名
    for(int i=0;i<columnNames.length;i++){
        Cell cell = row.createCell(i);
        cell.setCellValue(columnNames[i]);
    }
    //同理可以設置數據行
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        wb.write(os);
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] content = os.toByteArray();
    InputStream is = new ByteArrayInputStream(content);
    // 設置response參數,可以打開下載頁面
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (final IOException e) {
        throw e;
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
    return null;
    }
}

前臺代碼:

<input type="button" value="導出數據" onclick="download()"/>

//js代碼
function download(){
    var url="down.do?downExcel";
    window.open(url);
}

文章參考:http://my.oschina.net/aptx4869/blog/298507

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章