欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Java工具类——实体类列表写入excel

Java工具类——实体类列表写入excel

2025/4/22 4:53:50 来源:https://blog.csdn.net/qq_51137480/article/details/147309408  浏览:    关键词:Java工具类——实体类列表写入excel

Java工具类——实体类列表写入excel

/*** 将实体类 List 数据写入 Excel 文件* @param dataList 实体类对象列表* @param filePath Excel 文件路径* @param sheetName Sheet 名称* @param <T> 泛型类型* @throws IOException 文件操作异常* @throws IllegalAccessException 反射异常*/public static <T> void writeListToExcel(List<T> dataList, String filePath, String sheetName)throws IOException, IllegalAccessException {// 如果数据列表为空,直接返回if (dataList == null || dataList.isEmpty()) {return;}Workbook workbook;File file = new File(filePath);// 判断文件是否存在if (file.exists()) {// 文件存在,加载现有工作簿try (FileInputStream inputStream = new FileInputStream(file)) {workbook = new XSSFWorkbook(inputStream);}} else {// 文件不存在,创建新工作簿workbook = new XSSFWorkbook();}// 检查Sheet是否存在Sheet sheet = workbook.getSheet(sheetName);if (sheet != null) {// Sheet存在,先删除再创建(相当于清空)int sheetIndex = workbook.getSheetIndex(sheet);workbook.removeSheetAt(sheetIndex);sheet = workbook.createSheet(sheetName);} else {// Sheet不存在,直接创建sheet = workbook.createSheet(sheetName);}// 获取第一个对象的类信息Class<?> clazz = dataList.get(0).getClass();Field[] fields = clazz.getDeclaredFields();// 创建标题行Row headerRow = sheet.createRow(0);CellStyle headerStyle = createHeaderStyle(workbook);// 写入标题(属性名)for (int i = 0; i < fields.length; i++) {Cell cell = headerRow.createCell(i);cell.setCellValue(fields[i].getName());cell.setCellStyle(headerStyle);}// 写入数据行for (int i = 0; i < dataList.size(); i++) {Row row = sheet.createRow(i + 1);T item = dataList.get(i);for (int j = 0; j < fields.length; j++) {fields[j].setAccessible(true); // 允许访问私有字段Object value = fields[j].get(item);Cell cell = row.createCell(j);if (value != null) {if (value instanceof Number) {cell.setCellValue(((Number) value).doubleValue());} else if (value instanceof Boolean) {cell.setCellValue((Boolean) value);} else {cell.setCellValue(value.toString());}}}}// 自动调整列宽for (int i = 0; i < fields.length; i++) {sheet.autoSizeColumn(i);}// 写入文件try (FileOutputStream outputStream = new FileOutputStream(filePath)) {workbook.write(outputStream);} finally {workbook.close();}}/*** 创建标题行样式* @param workbook 工作簿* @return 单元格样式*/private static CellStyle createHeaderStyle(Workbook workbook) {CellStyle style = workbook.createCellStyle();Font font = workbook.createFont();font.setBold(true);style.setFont(font);style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);style.setBorderBottom(BorderStyle.THIN);style.setBorderTop(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);return style;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com