一、必須的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();
}
}
//這種方式直接可以在瀏覽器中下載
