JXLS 利用自定義Excel模板匯出excl
mavn 依賴
<!-- XLSTransformer相關 -->
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-reader</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.15</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>1.0.7</version>
</dependency>
Excel 模板例子:
List<ReportWorksheet> list = new ArrayList<ReportWorksheet>();
reportWorksheetList.drainTo(list);
// 定義一個Map,往裡面放入要在模板中顯示資料
Map<String, Object> model = new HashMap<String, Object>();
model.put("reportWorksheetList", list);
//呼叫之前寫的工具類,傳入模板路徑,輸出流,和裝有資料Map
//模板路徑
//String templateFileName=request.getSession().getServletContext().getRealPath("WEB-INF")+File.separator+"classes"+File.separator+"templates"+File.separator+"modules"+File.separator+"gen"+File.separator+"colleges.xls";
String templateFileName=request.getSession().getServletContext().getRealPath("WEB-INF")+File.separator+"reportlets"+File.separator+"worksheetDetailReportTemplates"+File.separator+"exportHoBySevenDays.xls";
XLSTransformer transformer = new XLSTransformer();
try{
transformer.transformXLS(templateFileName, model, fileName);
//輸入
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//輸出
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
try {
// 中文檔名支援
String encodedfileName = null;
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE")) {// IE
encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
encodedfileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
} else {
encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
response.setHeader("Content-Disposition", "attachment; filename=\""
+ encodedfileName + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int byteRead = 0;
byte[] buffer = new byte[8192];
while ((byteRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, byteRead);
}
bis.close();
bos.flush();
bos.close();
}catch (Exception e) {
e.printStackTrace();
}
匯出結果: