Excel文件导出
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.thoughtworks.xstream.core.util.Base64Encoder;
/**
* @Title TestController.java
* @Package cn.com.headfree.file.controller
* @Description excel文件导出
* @date 2019年12月19日 下午4:38:32
*/
public class TestController {
private static final Logger LOG = Logger.getLogger(TestController.class);
/**
* 导出excel数据模板
* @param req
* @param resp
* */
@SuppressWarnings("resource")
@RequestMapping("/excelExport")
@ResponseBody
public void excelExport(HttpServletRequest req,HttpServletResponse resp) {
InputStream fis = null;
ServletOutputStream out = null;
try {
ClassPathResource classPathResource = new ClassPathResource("file/template.xls");
fis = classPathResource.getInputStream();
//xls格式
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//xlsx格式
//XSSFWorkbook workbook = new XSSFWorkbook(fis);
resp.setContentType("application/force-download;charset=utf-8");
String fileName = "数据模板表";
//解决导出文件名中文乱码问题
// 获得请求头中的User-Agent
String agent = req.getHeader("User-Agent");
// 根据不同的客户端进行不同的编码
if (agent.contains("MSIE")) {// IE浏览器
fileName = URLEncoder.encode(fileName, "utf-8");
} else if (agent.contains("Firefox")) {// 火狐浏览器
Base64Encoder base64Encoder = new Base64Encoder();
fileName = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
} else {// 其它浏览器
fileName = URLEncoder.encode(fileName, "utf-8");
}
resp.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
out = resp.getOutputStream();
workbook.write(out);
} catch (Exception e) {
LOG.error("导出excel数据模板失败 ", e);
} finally {
//关闭文件输出流
try {
out.flush();
out.close();
fis.close();
} catch (IOException e) {
LOG.error("导出excel数据模板失败-关闭文件流失败 ", e);
}
}
}
}