You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.8 KiB

package com.zh.lingnuo.utils;
import org.apache.poi.xssf.usermodel.*;
import java.util.*;
/**
* 将List<Map<String,Object>> 类型数据导出到Excel文件
*/
public class ExcelExport {
/**
* src:定义下载的文件路径
*
* @param src
*
* @return
*/
public static XSSFWorkbook createExcel(LinkedHashMap<String, List<Map>> sheetList, String src) {
// 定义一个新的工作簿
XSSFWorkbook wb = new XSSFWorkbook();
for (Map.Entry<String, List<Map>> entry : sheetList.entrySet()) {
String sheetName = entry.getKey();
List<Map> list = entry.getValue();
if( list.size() == 0){
continue;
}
// 创建一个Sheet页
XSSFSheet sheet = wb.createSheet(sheetName);
//设置行高
sheet.setDefaultRowHeight((short) (2 * 256));
//设置列宽
sheet.setColumnWidth(0, 4000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 4000);
XSSFFont font = wb.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 16);
//获得表格第一行
XSSFRow row = sheet.createRow(0);
//根据需要给第一行每一列设置标题
int rowCellIndex = 0;
XSSFCell cell = row.createCell(rowCellIndex);
if (null == list || list.size() == 0) {
return wb;
}
Set<Object> keys = list.get(0).keySet();
Object[] keysArray = keys.toArray();
for (Object key : keys) {
cell = row.createCell(rowCellIndex);
cell.setCellValue(key.toString());
rowCellIndex++;
}
XSSFRow rows;
XSSFCell cells;
//循环拿到的数据给所有行每一列设置对应的值
for (int i = 0; i < list.size(); i++) {
// 在这个sheet页里创建一行
rows = sheet.createRow(i + 1);
// 该行创建一个单元格,在该单元格里设置值
rowCellIndex = 0;
for (Object s : keysArray) {
cells = rows.createCell(rowCellIndex);
cells.setCellValue(null == list.get(i).get(s) ? "" : list.get(i).get(s).toString());
rowCellIndex++;
}
}
}
// try {
// File file = new File(src);
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// wb.write(fileOutputStream);
// wb.close();
// fileOutputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
return wb;
}
}