欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-13 14:20:30
...

/**
*
* 使用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;
}


相关标签: Excel操作