导出工具类
list
* 要导出的数据集
* fileName
* 模板名称
* exportName
* 下载文件名
* rowIndex
* 行号下标,从0开始。
* alis
* 字段别名–数组
*
public void exportExcel(HttpServletRequest request, HttpServletResponse response,
List<?> list, String fileName, String exportName, int rowIndex,
String[] alisName, String[] alis) {
if (null != list) {
// 获取模板
HSSFWorkbook workBook = null;
String filePath = request.getServletContext().getRealPath("/") + "\\temp\\" + fileName;
try {
HSSFWorkbook workbook1 = new HSSFWorkbook();
workbook1.createSheet();
workbook1.createSheet();
FileOutputStream fileOut = new FileOutputStream(filePath);
workbook1.write(fileOut);
fileOut.close();
response.setContentType("application/x-download");
String filenamedisplay = URLEncoder.encode(exportName, "UTF-8"); // 下载文件时显示的文件保存名称
response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);
workBook = new HSSFWorkbook(new FileInputStream(filePath));
// 获取第一个sheet页。
HSSFSheet sheet = workBook.getSheetAt(0);
// 设置边框
HSSFCellStyle cellStyle = workBook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 设置边框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
HSSFCell cell = null;
Map<String, Object> map = null;
Date date = null;
HSSFRow row = sheet.createRow(rowIndex++);
// 创建头
for (int k = 0; k < alisName.length; k++) {
String alisNameString = alisName[k];
cell = row.createCell(k);
cell.setCellValue(alisNameString);
cell.setCellStyle(cellStyle);
}
for (int i = 0; i < list.size(); i++) {
if(list.get(i) instanceof Map){
map = (Map<String, Object>) list.get(i);
}else{
map = BeanToMap.ConvertObjToMap(list.get(i));
}
// 创建行 --创建序号列
row = sheet.createRow(rowIndex++);
cell = row.createCell(0);
cell.setCellValue(i + 1 + "");
cell.setCellStyle(cellStyle);
for (int j = 0; j < alis.length; j++) {
String alisColumn = alis[j];
cell = row.createCell(j + 1);
if(map.get(alisColumn) instanceof Date){
date = (Date) map.get(alisColumn);
cell.setCellValue(DateUtil.DateToString(date, "yyyy-MM-dd HH:mm:ss"));
} else {
cell.setCellValue(map.get(alisColumn) == null ? "": map.get(alisColumn).toString());
}
cell.setCellStyle(cellStyle);
}
}
// 将读取的excel数据直接写入前端,进行导出
workBook.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
System.out.println("导出异常!");
} finally {
try {
if (workBook != null)
workBook.close();
response.flushBuffer();
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("导出异常!");
}
}
}
}