import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
public static <T> void createExcel(List<T> dataList, Class<T> cls, Map<String, Integer> mergeMap, String fileName) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
// 创建标题行
Row titleRow = sheet.createRow(0);
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
titleRow.createCell(i).setCellValue(fields[i].getName());
}
// 填充数据
int rowIndex = 1;
for (T data : dataList) {
Row dataRow = sheet.createRow(rowIndex);
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
try {
Object value = field.get(data);
dataRow.createCell(i).setCellValue(value == null ? "" : value.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
rowIndex++;
}
// 合并行
for (Map.Entry<String, Integer> mergeEntry : mergeMap.entrySet()) {
String[] mergeInfo = mergeEntry.getKey().split("-");
int firstRow = Integer.parseInt(mergeInfo[0]);
int lastRow = Integer.parseInt(mergeInfo[1]);
int col = mergeEntry.getValue();
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, col, col));
}
// 写入文件
FileOutputStream out = new FileOutputStream(fileName);
workbook.write(out);
out.close();
workbook.close(
评论已关闭