大家好,又见面了,我是你们的朋友全栈君。
先上代码
java code:
代码语言:javascript复制<pre name="code" class="java">package cn.export.util;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 导出文件util
* @author
*/
public class ExportUtil {
@SuppressWarnings("unchecked")
public static void exportData(HttpServletRequest req, HttpServletResponse resp, List results,String fileName,
String year,String quarter, String filePath) throws Exception{
FileInputStream fis = null;
ServletOutputStream os = null;
XLSTransformer transformer = new XLSTransformer();
Map params = new HashMap();
params.put("year", year);
params.put("quarter", quarter);
params.put("results", results);
fis = new FileInputStream(filePath);
resp.addHeader("Content-Disposition", "attachment;filename=" URLEncoder.encode(fileName, "UTF-8") ".xls");
resp.setContentType("application/vnd.ms-excel;charset=gbk");
resp.setHeader("Location", URLEncoder.encode(fileName,"UTF-8") ".xls");
HSSFWorkbook wb = transformer.transformXLS(fis, params);
os = resp.getOutputStream();
wb.write(os);
os.flush();
os.close();
fis.close();
}
}
代码语言:javascript复制
java code:
代码语言:javascript复制package cn.export.com;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.export.util.ExportUtil;
public class ExportServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
try {
String fileName = "服装销售统计";
List results = new ArrayList();
for(int i = 0; i < 3; i ){
Map resMap = new HashMap();
resMap.put("id", i);
resMap.put("name", "女装" i);
resMap.put("area", "广州");
resMap.put("traffic", "高铁");
resMap.put("level", "A");
resMap.put("time", "2014/09/19");
resMap.put("operator", "张三");
resMap.put("remark", "销售良好");
results.add(i, resMap);
}
URL url = this.getClass().getClassLoader().getResource("");
String filePath = url.getPath() "doc/fz.xls";
ExportUtil.exportData(req, resp, results, fileName, "2014", "2", filePath);
} catch (Exception e) {
}finally{
try {
} catch (Exception e) {
}
}
}
}
所需jar包:
所需jar包下载: 点击这里 (该功能单独测试,没有和其他框架整合)
Excel表模板格式:
(注:excel获取数据的方式: ${results.get(“key”)} ,key为上面代码中map的key)
结果显示:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163870.html原文链接:https://javaforall.cn