一、必须的maven依赖(可在jxls的官网上去找最新版本):
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.4.6</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.15</version>
</dependency>
二、设置Excel模板(新建一个Excel文档,按如下步骤设置),将新建的文档放到项目中(本案例是放到项目的resource目录下,其他目录不知道可以不)
三、代码编写:
@RequestMapping(value = "exportDeviceModelMsg",method = RequestMethod.GET)
@ResponseBody
public void exportDeviceModelMsg(HttpServletRequest request, HttpServletResponse response) {
try {
List<MyTest> myTestList = myTestService.findAll(); //获取列表数据
InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/test.xls"); //得到文档的路径
//列表数据将存储到指定的excel文件路径,这个路径是在项目编译之后的target目录下
FileOutputStream out = new FileOutputStream("target/classes/excel/aaaa.xls");
//这里的context是jxls框架上的context内容
org.jxls.common.Context context = new org.jxls.common.Context();
//将列表参数放入context中
context.putVar("myTestList", myTestList);
//将List<Exam>列表数据按照模板文件中的格式生成到scoreOutput.xls文件中
JxlsHelper.getInstance().processTemplate(in, out, context);
//下面步骤为浏览器下载部分
//指定数据生成后的文件输入流(将上述out的路径作为文件的输入流)
FileInputStream fileInputStream = new FileInputStream("target/classes/excel/aaaa.xls");
//导出excel文件,设置文件名
String filename = URLEncoder.encode("test信息.xls", "UTF-8");
//设置下载头
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
ServletOutputStream outputStream = response.getOutputStream();
//将文件写入浏览器
byte[] bys = new byte[fileInputStream.available()];
fileInputStream.read(bys);
outputStream.write(bys);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//这种方式直接可以在浏览器中下载