生成EXCEL的公共方法(使用模板)


/**
*
* 使用poi方式生成excel报表 <br>
* 〈功能详细描述〉
*
* @param exportList:数据列表
* @param columnNames:字段的列明数组(对应的就是Map中的Key值)
* @param templateName:Excel模板名称
* @param fileName:生成的Excel文件名
* @param index:使用第几个Sheet页
* @param insertLine:从Excel中的第几行开始插入数据
* @param request
* @param response
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static void usePoiExportDatas(List<Map<String, Object>> exportList, String[] columnNames,
String templateName, String fileName, int index, int insertLine, HttpServletRequest request,
HttpServletResponse response) {
// 获取Excel模板文件路径
String excelModelPath = getExcelModelPath(templateName, request);

OutputStream os = null;
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(excelModelPath));
Workbook work = new HSSFWorkbook(is);
// 得到excel的第index个sheet页
Sheet sheet = work.getSheetAt(index);

// 遍历数据集列表,每条记录对应Excel文件中的一行
for (int i = 0; i < exportList.size(); i++) {
Map<String, Object> dataMap = exportList.get(i);

// 生成Excel中的行
Row row = sheet.createRow(i + insertLine - 1);
for (int j = 0; j < columnNames.length; j++) {
// 生成Excel中的列
Cell cell = row.createCell(j);
// 为该列赋值
cell.setCellValue(MapUtils.getString(dataMap, columnNames[j], ""));
}
}

response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
os = response.getOutputStream();
work.write(os);
} catch (IOException e) {
logger.error("IO异常");
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
}

private static String getExcelModelPath(String templateName, HttpServletRequest request) {
StringBuilder filePath = new StringBuilder(50);
filePath.append(request.getSession().getServletContext().getRealPath("/")).append(File.separator)
.append("report").append(File.separator).append("template").append(File.separator);
// Excel模板路径
String modelFilePath = filePath.toString() + templateName;

return modelFilePath;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值