适用于将查询的结果集直接根据模板导出excel
首先导入jar包
<!-- 配置模板导出工具包 -->
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0.6</version>
</dependency>
下面是导出方法:
/** 将查询的po对象集合导出 */
public void exportResult(HttpServletRequest request, HttpServletResponse response, PwCalculationResultsMain queryMain) throws Exception
{
//查询导出的实体集合
List<PwCalculationResultsMain> list = pwCalculationResultsMainService.queryList(queryMain);
HashMap<String, Object> dataMap = new HashMap<>();
if (CollectionUtils.isEmpty(list))
{
return;
}
dataMap.put(CommonConstant.RESULT, list);
ServletOutputStream output = null;
InputStream inputStream = null;
try
{
inputStream = ExcelTemplateUtil.getInstance().genExcelFileByTemplate(dataMap, CommonConstant.PWGCCS_FILEPATH);
if (inputStream != null)
{
response.reset();
response.addHeader(CommonConstant.HEADER_NAME, CommonConstant.HEADER_VALUE_PREFIX + URLEncoder.encode(CommonConstant.PWGCCS_EXP_FILENAME, CommonConstant.UTF_8));
output = response.getOutputStream();
byte[] buffer = new byte[524288];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
response.flushBuffer();
}
}
finally
{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(output);
}
}
/**
* 将内容填充到excel模版生成文件
* @param data
* @param tempPath
* @return
* @throws Exception
*/
public InputStream genExcelFileByTemplate(Map<String, Object> data, String tempPath) throws Exception
{
// 模版文件流(利用这个方法获取到的流是已经关闭的,后面WorkbookFactory.create(is)时报异常-流关闭)
// InputStream tempStream =
// ExcelTemplateUtil.class.getResourceAsStream(tempPath);
// 因此换成了绝对路径获取模板的方法
InputStream inputStream = new FileInputStream(tempPath);
// transformer转到Excel
XLSTransformer transformer = new XLSTransformer();
// 将数据添加到模版中生成新的excel文件
Workbook workbook = transformer.transformXLS(inputStream, data);
// workbook转换成流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] barray = bos.toByteArray();
return new ByteArrayInputStream(barray);
}