1. 程式人生 > >spring mvc 通過流直接匯出文字格式(excle,csv類似)

spring mvc 通過流直接匯出文字格式(excle,csv類似)

   一邊我們匯出檔案的時候,首先會先在伺服器生成檔案,然後再通過 (路徑+檔名)的方式 來匯出。。

   現在呢, 我們不需要在伺服器生成檔案, 直接匯出,應該怎樣做呢?

   看demo吧!

package com.broadtech.unicom.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.broadtech.unicom.base.BaseController;


@Controller
@RequestMapping("/ExportFileController.do")
public class ExportFileController extends BaseController{
@RequestMapping(params = "method=exportDownload")
public void exportDownload(String fileUrl, HttpServletRequest request, HttpServletResponse response) {
try {
if (fileUrl == null || "".equals(fileUrl)) {
response.getWriter().write("Parameter type is not correct!");
return;
}
fileUrl = URLDecoder.decode(fileUrl, "UTF-8");
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);


response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso8859-1"));
if (AbstractExport.EXPORT_SUFFIX_ZIP.equals(suffix)) {
response.setContentType("application/x-zip-compressed");
} else if (AbstractExport.EXPORT_SUFFIX_EXCEL.equals(suffix)) {
response.setContentType("application/vnd.ms-excel");
} else if (AbstractExport.EXPORT_SUFFIX_CSV.equals(suffix)) {
response.setContentType("application/oct-stream");
} else if (AbstractExport.EXPORT_SUFFIX_TEXT.equals(suffix)) {
response.setContentType("text/plain");
} else if (AbstractExport.EXPORT_SUFFIX_PNG.equals(suffix)) {
response.setContentType("image/x-png");
} else {
response.getWriter().write("Parameter type is not correct!");
return;
}
PrintWriter output = response.getWriter();
String outStream = "helloword";

for(int i = 0; i < 10; i ++){
output.println(outStream);
}
output.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


class AbstractExport{
static String EXPORT_SUFFIX_ZIP = "zip";
static String EXPORT_SUFFIX_EXCEL = "xls";
static String EXPORT_SUFFIX_CSV = "csv";
static String EXPORT_SUFFIX_TEXT = "text";
static String EXPORT_SUFFIX_PNG = "png";
}