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

本文展示了如何在Spring MVC中避免在服务器上生成文件,而是直接通过流的方式导出文本格式(如Excel、CSV)。通过`ExportFileController`控制器中的`exportDownload`方法,结合HttpServletResponse设置响应头并利用PrintWriter输出内容,实现了动态生成并下载特定类型的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   一边我们导出文件的时候,首先会先在服务器生成文件,然后再通过 (路径+文件名)的方式 来导出。。

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

  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值