public class ExportExcel{
HttpServletRequest request;
HttpServletResponse response;
List saff;
String fileName;
public ExportExcel(HttpServletRequest request, HttpServletResponse response, List saff, String fileName ){
this.request=request;
this.response=response;
this.saff=saff;
this.fileName=fileName;
}
public void exportProject(String sourceName)throws Exception{
Map<String,Object> map=new HashMap<>();
map.put("fileName",fileName);
map.put("testforms",saff);
//获得模板路径
String path=request.getServletContext().getRealPath("excel_export");
String wjpath=path+ File.separator+sourceName;
//准备输出流
OutputStream os=null;
try {
//设置响应头
response.setContentType("application/x-excel");
//response.setHeader("Content-Disposition", "attachment;filename=studentInfo.xls");
response.setHeader("Content-Disposition", "attachment;filename="+new String((fileName+".xls").getBytes(),"iso8859-1"));
response.setContentType("application/ms-excel");
os = response.getOutputStream();
XLSTransformer transformer = new XLSTransformer();
try {
//获得模板的输入流
InputStream in = new BufferedInputStream(new FileInputStream(wjpath));
//将beans通过模板输入流写到workbook中
Workbook workbook = transformer.transformXLS(in, map);
//将workbook中的内容用输出流写出去
workbook.write(os);
os.flush();
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
HttpServletRequest request;
HttpServletResponse response;
List saff;
String fileName;
public ExportExcel(HttpServletRequest request, HttpServletResponse response, List saff, String fileName ){
this.request=request;
this.response=response;
this.saff=saff;
this.fileName=fileName;
}
public void exportProject(String sourceName)throws Exception{
Map<String,Object> map=new HashMap<>();
map.put("fileName",fileName);
map.put("testforms",saff);
//获得模板路径
String path=request.getServletContext().getRealPath("excel_export");
String wjpath=path+ File.separator+sourceName;
//准备输出流
OutputStream os=null;
try {
//设置响应头
response.setContentType("application/x-excel");
//response.setHeader("Content-Disposition", "attachment;filename=studentInfo.xls");
response.setHeader("Content-Disposition", "attachment;filename="+new String((fileName+".xls").getBytes(),"iso8859-1"));
response.setContentType("application/ms-excel");
os = response.getOutputStream();
XLSTransformer transformer = new XLSTransformer();
try {
//获得模板的输入流
InputStream in = new BufferedInputStream(new FileInputStream(wjpath));
//将beans通过模板输入流写到workbook中
Workbook workbook = transformer.transformXLS(in, map);
//将workbook中的内容用输出流写出去
workbook.write(os);
os.flush();
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
demo下载地址 http://download.youkuaiyun.com/download/maple980326/9959219
相关博客地址: http://blog.youkuaiyun.com/yuliqi0429/article/details/41907711