您的位置:首页 > 编程语言 > Java开发

spring mvc 通过流直接导出文本格式(excle,csv类似)

2015-11-06 18:05 573 查看
   一边我们导出文件的时候,首先会先在服务器生成文件,然后再通过 (路径+文件名)的方式 来导出。。

   现在呢, 我们不需要在服务器生成文件, 直接导出,应该怎样做呢?

  

   看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";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: