代码
@RequestMapping(value="/exexcel")
public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException{
//打印程序当前路径
System.out.println(System.getProperty("user.dir"));
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
String jasperPath = servletContext.getRealPath(
"/WEB-INF/jasper/report13.jasper");
Map<String,Object> params = new HashMap<String,Object>();
//UserJs.getUser()是List类型数据源
JRDataSource dataSource = new JRBeanCollectionDataSource(UserJs.getUser(), true);
//print文件
JasperPrint print = JasperFillManager.fillReport(jasperPath, params, dataSource);
//以附件形式保存文件
String generateFileName = "My文件.xlsx";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename="
+ URLEncoder.encode(generateFileName,"utf8"));
//设置导出时参数
SimpleXlsxReportConfiguration conf = new SimpleXlsxReportConfiguration();
conf.setWhitePageBackground(false);
conf.setDetectCellType(true);
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setConfiguration(conf);
//设置输入项
ExporterInput exporterInput = new SimpleExporterInput(print);
exporter.setExporterInput(exporterInput);
//设置输出项
OutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(response.getOutputStream());
exporter.setExporterOutput(exporterOutput);
exporter.exportReport();
}
UserJs.java
package com.xie.vo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 用于测试jasperReport
* @author xie
*
*/
public class UserJs {
private int id;
private String name;
private int age;
private String title;
public UserJs() {
super();
}
public UserJs(int id, String name, int age, String title) {
super();
this.id = id;
this.name = name;
this.age = age;
this.title=title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static List<UserJs> getUser(){
List<UserJs> listUserJs=new ArrayList<>();
listUserJs.add(new UserJs(0,"xx",20,"user表"));
listUserJs.add(new UserJs(1,"写好",23,"user表"));
listUserJs.add(new UserJs(2, "pp", 32,"user表"));
return listUserJs;
}
public static Map<String,Object> getUserMap(){
Map<String,Object> map=new HashMap<>();
map.put("id",0);
map.put("name","好啊");
map.put("age", 23);
map.put("title", "表格");
return map;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
}
说明
参考(复制)了网上好多人的,比如:
http://blog.csdn.net/wangjun5159/article/details/51152403
http://blog.csdn.net/wangjun5159/article/details/51152403
http://blog.csdn.net/zhuhuiby/article/details/8569516