1. 程式人生 > >Springmvc 生成並且下載檔案--直接在瀏覽器下載。

Springmvc 生成並且下載檔案--直接在瀏覽器下載。

首先,我有一個jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="application/javascript">
    function download(){
        var url="http://localhost:8080/wdxend/excelexport/testDownload";
        window.open(url);
    }
</script>

<body>

<input type="button" value="匯出資料" onclick="download()"/>
</body>
</html>

很久不玩,都不記得jsp怎麼配得了。

<bean id="jspViewResolver"
		  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/static/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
這是一個訪問用的Controller:用來跳轉到下載頁面。
@RequestMapping("testjsp")
    public ModelAndView test(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("status");
        return modelAndView;
    }

這是一個下載的Controller

@RequestMapping("testDownload")
    public String testDownload(HttpServletRequest request, HttpServletResponse response/*, @RequestBody PieceCostParam pieceCostParam*/) throws Exception{
        PieceCostParam pieceCostParam = new PieceCostParam();
        PieceCostQuery pieceCostQuery = new PieceCostQuery();
        pieceCostQuery.setCompanyName("杭州電子放假大學");
        pieceCostParam.setPieceCostQuery(pieceCostQuery);
        return excelExportService.testDownload(request, response, pieceCostParam);
    }
這是service:
@Override
    public String testDownload(HttpServletRequest request, HttpServletResponse response, PieceCostParam pieceCostParam) throws Exception{
        String fileName="excel檔案";
        //填充projects資料
        List<PieceCostVO> projects=costRelatedService.getAllPieceCost(pieceCostParam);
        List<Map<String,Object>> list=createExcelRecord(projects);
        String columnNames[]={"序號","機構名稱","購買時間","資料包名稱","購買線索條數","線索單價","線索收費"};//列名
        String keys[]    =     {"id","name","purcahseTime","packName","num","cost","sumcost"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).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;
    }


    private List<Map<String, Object>> createExcelRecord(List<PieceCostVO> projects) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        PieceCostVO project=null;
        for (int j = 0; j < projects.size(); j++) {
            project=projects.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("id", j);
            mapValue.put("name", project.getCompanyName());
            mapValue.put("purcahseTime", project.getPurchaseTime());
            mapValue.put("packName", project.getDataPackName());
            mapValue.put("num", project.getDataSum());
            mapValue.put("cost", project.getDataCost());
            mapValue.put("sumcost", project.getCostSum());
            listmap.add(mapValue);
        }
        return listmap;
    }

這是ExcelUtil類:
/**
 * 匯出Excel文件工具類
 * [@author](http://my.oschina.net/arthor) 那位先生
 * [@date](http://my.oschina.net/u/2504391) 2014-8-6
 * */
public class ExcelUtil {

    /**
     * 建立excel文件,
     * [@param](http://my.oschina.net/u/2303379) list 資料
     * @param keys list中map的key陣列集合
     * @param columnNames excel的列名
     * */
    public static Workbook createWorkBook(List<Map<String, Object>> list, String []keys, String columnNames[]) {
        // 建立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);

        // 建立兩種單元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 建立兩種字型
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 建立第一種字型樣式(用於列名)
        f.setFontHeightInPoints((short) 10);
        f.setColor(IndexedColors.BLACK.getIndex());
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // 建立第二種字型樣式(用於值)
        f2.setFontHeightInPoints((short) 10);
        f2.setColor(IndexedColors.BLACK.getIndex());

//        Font f3=wb.createFont();
//        f3.setFontHeightInPoints((short) 10);
//        f3.setColor(IndexedColors.RED.getIndex());

        // 設定第一種單元格的樣式(用於列名)
        cs.setFont(f);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setAlignment(CellStyle.ALIGN_CENTER);

        // 設定第二種單元格的樣式(用於值)
        cs2.setFont(f2);
        cs2.setBorderLeft(CellStyle.BORDER_THIN);
        cs2.setBorderRight(CellStyle.BORDER_THIN);
        cs2.setBorderTop(CellStyle.BORDER_THIN);
        cs2.setBorderBottom(CellStyle.BORDER_THIN);
        cs2.setAlignment(CellStyle.ALIGN_CENTER);
        //設定列名
        for(int i=0;i<columnNames.length;i++){
            Cell cell = row.createCell(i);
            cell.setCellValue(columnNames[i]);
            cell.setCellStyle(cs);
        }
        //設定每行每列的值
        for (short i = 1; i < list.size(); i++) {
            // Row 行,Cell 方格 , Row 和 Cell 都是從0開始計數的
            // 建立一行,在頁sheet上
            Row row1 = sheet.createRow((short) i);
            // 在row行上建立一個方格
            for(short j=0;j<keys.length;j++){
                Cell cell = row1.createCell(j);
                cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString());
                cell.setCellStyle(cs2);
            }
        }
        return wb;
    }

}

差不多就是這樣啦,你要是直接把程式碼拷過去肯定會報錯啦,因為你沒有我的實體類,在你找到我的程式碼之前肯定知道excel的操作啦,那這些你應該也能看懂,要是不知道,建議還是先看看excel的操作吧。



相關推薦

Springmvc 生成並且下載檔案--直接瀏覽器下載

首先,我有一個jsp頁面:<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title<

SpringMVC筆記八之檔案上傳下載

一、檔案上傳 1、普通檔案上傳 新建頁面WebContent/file.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

PHP 下載檔案瀏覽器

方法一 a標籤H5屬性download屬性,<a download='test.txt' href='http://www.baidu.com'>下載test.txt檔案</a>

c++下載檔案(考慮瀏覽器緩衝)

CString DownloadFile(CString strURL,int type) { //初始化資料 //BYTE datalen[5]; int len = 0; CHttpFile* pfile = NULL; CInternetSession se

關於Ajax無法下載檔案瀏覽器本地的問題

最近在做網站的時候遇到這樣一個功能,在如圖所示的頁面中,需要使用者點選連結的時候,能夠以非同步Ajax的方式判斷伺服器中是否儲存有相應的Excel檔案,如果沒有的話就提示使用者沒有找到,如果有的話就下

SpringMVC教程3【檔案上傳下載,靜態資源處理及資料校驗】

一,檔案上傳 web.xml配置通用 <?xml version="1.0" encoding=&q

谷歌瀏覽器下載|谷歌瀏覽器下載

記得第一次開始使用谷歌瀏覽器的時候還在讀初中,那時候就喜歡倒騰電腦,裝了個360,從那裡面下了很多瀏覽器,還買了很多本電腦愛好者的雜誌,喜歡拿各種軟體做對比谷歌瀏覽器下載連結軟體介紹谷歌瀏覽器是由Google開發的一款操作簡單、高效的瀏覽器。而它最大的亮點就是其多程序架構,它不會因為一個站點從而影響所有的視窗

HttpServletResponse下載檔案(中文名稱下載)-------手動編碼實現下載

DownloadServlet:   package com.yuming.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; impo

java多執行緒下載檔案和斷點下載

多執行緒,斷點下載檔案 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOExcept

Http 下載檔案,指定下載位置

 HTTP協議簡介   下載檔案是電腦與WEB伺服器互動的過程,它們互動的"語言"的專業名稱是協議。傳送檔案的協議有多種,最常用的是HTTP(超文字傳輸協議)和FTP(檔案傳送協議),我採用的是HTTP。 HTTP協議最基本的命令只有三條:Get、Post和Head。

JS下載檔案|無重新整理下載檔案

後臺程式碼Handler.ashx <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.

springMvc生成匯出excel檔案

/** * 匯出商品excel表格 * @throws UnsupportedEncodingException  */@RequestMapping(value = "/exceptProduct", method = RequestMethod.GET)public v

phpcms下載直接顯示下載真實地址方法

進入phpcms後臺--“內容”--“內容相關設定”--“模型管理”,點選進去之後選擇“下載模型”--點選“欄位管理”--“本地下載” 把選項修改為圖中紅色部分的選項,點選檔案連結的時候就不需要跳轉到點選下載頁面(下圖)自動下載了。

Androidstudio2.3.1編譯生成的APK檔案直接拿來安裝時崩潰以及臨時解決辦法

今天做完小專案之後,想把apk檔案通過QQ發給別人試試,按照平常在app\build\outputs\apk目錄下就可以找到,結果將apk拿給別人安裝的時候發現崩潰,,之前除錯的時候一直用手機連線電腦直接執行,沒有出現錯誤: Androidstudio的Log出現錯誤資訊如

libcurl post/get上傳下載檔案 以及斷點下載(操作libcurl 實現斷點下載(續點續傳))

各位親 有時間可以去看看我的  “金駿家居淘寶店” http://jinjun1688.taobao.com/shop/view_shop.htm?tracelog=twddp 買時說明在我的部落格看到有優惠哦 還有意外禮品贈送  真正的程式設計師淘寶店 標頭檔案

okhttp2.6使用get和post 上傳和下載檔案 普通的下載

為了寫部落格所以沒有封裝 使用的時候OkHttpClien() new 一次就可以了 不用new很多次 implementation 'com.squareup.okhttp:okhttp:2.6.0'public void downPhotos(String url

80埠常被佔用的程式 Apache如何每天生成獨立日誌檔案(access_log和error_log)magic_quotes_runtime,get_magic_quotes_gpc,ini_

80埠常被佔用的程式  1,iis不我說,停止即可. 2.安裝sqlserver 2008 後,SQL Server Reporting Services佔用, 3.安裝VS後,MSDEPLOYAGENTSERVICE/佔用 安裝WebDeploy 安裝WebDeplo

Java通用的Excel檔案生成工具類,支援生成檔案瀏覽器直接下載

<span style="font-size:14px;">java通用的Excel檔案建立方法,支援同文件多tab頁建立。只需要呼叫靜態方法,傳遞List<String>表頭和List<Map>資料集合等,即可生成Excel檔案。 p

匯出多級資料到excel並且生成zip壓縮檔案下載

為了實現以下如圖的效果 首先:需要的jar包 jxl      生成excel ant (org.apache.tools.ant) 生成zip壓縮檔案   1.建立目錄結構,最後生成壓縮包: String realPa

直接瀏覽器下載檔案而不開啟

直接讓客戶端瀏覽器下載已知型別(*.doc)的檔案  ,而不使用關聯程式開啟。         Web開發人員都有過這樣的疑問,如何讓一個檔案,尤其是一個已知型別的檔案(*.doc),傳送到客戶端,直接提示讓瀏覽者下載,而不是用與它相關聯的程式開啟。     以前我們最