导出excel文件
需求中有一个功能是导出工资信息
在后端直接导出到项目根目录下
public String createExcel(List<Map<String, String>> mapList,String filename, String title) {
//获取数据源的 key, 用于获取列数及设置标题
Map<String, String> map = mapList.get(0);
Set<String> stringSet = map.keySet();
ArrayList<String> headList = new ArrayList<>(stringSet);
//定义一个新的工作簿
XSSFWorkbook wb = new XSSFWorkbook();
//创建一个Sheet页
XSSFSheet sheet = wb.createSheet(title);
//设置行高
sheet.setDefaultRowHeight((short) (2 * 256));
//为有数据的每列设置列宽
for (int i = 0; i < headList.size(); i++) {
sheet.setColumnWidth(i, 8000);
}
//设置单元格字体样式
XSSFFont font = wb.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 20);
//在sheet里创建第一行,并设置单元格内容为 title (标题)
XSSFRow titleRow = sheet.createRow(0);
XSSFCell titleCell = titleRow.createCell(0);
titleCell.setCellValue(title);
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headList.size() - 1));
// 创建单元格文字居中样式并设置标题单元格居中
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
titleCell.setCellStyle(cellStyle);
//获得表格第二行
XSSFRow row = sheet.createRow(1);
//根据数据源信息给第二行每一列设置标题
for (int i = 0; i < headList.size(); i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(headList.get(i));
cell.setCellStyle(cellStyle);
}
XSSFRow rows;
XSSFCell cells;
//循环拿到的数据给所有行每一列设置对应的值
for (int i = 0; i < mapList.size(); i++) {
//在这个sheet页里创建一行
rows = sheet.createRow(i + 2);
//给该行数据赋值
for (int j = 0; j < headList.size(); j++) {
String value = String.valueOf(mapList.get(i).get(headList.get(j)));
cells = rows.createCell(j);
cells.setCellValue(value);
cells.setCellStyle(cellStyle);
}
}
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// 使用项目根目录, 文件名加上时间戳
String path = System.getProperty("user.dir") + "\\" + filename + dateFormat.format(date) + ".xlsx";
System.out.println("Excel文件输出路径: "+path);
try {
File file = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(file);
wb.write(fileOutputStream);
wb.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
点击生成工资