在这里分享一下我在项目中用到的Excel导出模板的功能,直接看代码:
package com.wdcloud.wjdc.utils.export;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelUtil {
/** log **/
private static Log log = LogFactory.getLog(ExcelUtil.class);
public static Boolean exportTemplate(HttpServletResponse response, String templateFile, Object data, String fileName) {
try {
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
OutputStream outStream = new BufferedOutputStream(response.getOutputStream());
Map<String, Object> map = new HashMap<String, Object>();
map.put("data", data);
InputStream inputStream = ExcelUtil.class.getClassLoader().getResourceAsStream(templateFile);
File outFile = File.createTempFile("temp", "xls");
byte[] b = saveOutput(map, inputStream, outFile);
System.out.println(b);
outStream.write(b);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] saveOutput(Map<String, Object> data, InputStream templateFile, File outFile) {
try {
XLSTransformer transformer = new XLSTransformer();
Workbook workbook = transformer.transformXLS(templateFile, data);
//TODO 图片处理
workbook.write(new FileOutputStream(outFile.getPath()));
FileInputStream inStream = new FileInputStream(outFile);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
for (int n = 0; (n = inStream.read(b)) != -1;) {
outStream.write(b, 0, n);
}
inStream.close();
outStream.close();
return outStream.toByteArray();
} catch (Exception e) {
log.error("catch:" + ExceptionUtils.getStackTrace(e));
}
return null;
}
}
templateFile:导出文件路径;
fileName:导出文件名称;
data: 需要导出的数据;
下面是导出用到的模板:
业务编号 公开范围 题目简称 是否有效 题目类型 创建时间 创建人名称 版本号 题目分类 发布状态
<jx:forEach items="${data}" var="tm">
${tm.tmywbh} ${tm.gkfwDesc} ${tm.tmjc} ${tm.sfyxDesc} ${tm.tmlxDesc} ${tm.cjsj} ${tm.cjrmc} ${tm.zxgxcd} ${tm.flmc} ${tm.fbztDesc}
</jx:forEach>