注意要引入新的jar
我把jar放到资源里
//生成excel
public static String doExcel(String from, Map beans, String to,HttpServletRequest request) {
String path = request.getSession().getServletContext().getRealPath("//template");//模板地址String pathdown = request.getSession().getServletContext().getRealPath("//upload");//上传地址
XLSTransformer transformer = new XLSTransformer();
String sfrom = path + File.separator + from;// 模板文件
String sto = pathdown + File.separator + to;// 要生成的文件
try {
transformer.transformXLS(sfrom, beans, sto);
} catch (ParsePropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sto;
}
// 下载
public static void doDownLoad(String path, String name,HttpServletResponse response) {
try {
response.reset();
response.setHeader("Content-disposition","attachment;success=true;filename ="+ URLEncoder.encode(name, "utf-8"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
File uploadFile = new File(path);
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
// 弹出下载对话框
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/execlbanlace")
public String execlbanlace(HttpSession session, HttpServletRequest request, HttpServletResponse response){
Map<String,String> map = new HashMap<String,String>();
List<userResource> list=NumberDao.SearchRes(map);
Map<String,Object> beans = new HashMap<String,Object>();
beans.put("balancelist",list);
IPTimeStamp its= new IPTimeStamp("");
String fileName = its.getIPTimeStampRand();
String path=doExcel("号码资源模板.xlsx" , beans , "号码资源_"+fileName+".xlsx",request);
// doDownLoad(path, "balance.xls",response);
return null;
}
注意模板内代码要和beans的一致