java封装一套批量导出对象到excel工具类代码

动态 未结 0 103
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是一个简单的Java工具类,用于将对象列表批量导出到Excel文件中: ``` import java.io.FileOutputStream; import java.lang.reflect.Field; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ExcelExportUtil { /** * 将对象列表批量导出到Excel文件中 * @param dataList 对象列表 * @param filePath 导出文件路径 * @throws Exception */ public static void export(List dataList, String filePath) throws Exception { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(); // 写入表头 Row headerRow = sheet.createRow(0); Field[] fields = dataList.get(0).getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(fields[i].getName()); } // 写入数据 for (int i = 0; i < dataList.size(); i++) { T data = dataList.get(i); Row row = sheet.createRow(i + 1); for (int j = 0; j < fields.length; j++) { Field field = fields[j]; field.setAccessible(true); Object value = field.get(data); Cell cell = row.createCell(j); if (value != null) { cell.setCellValue(value.toString()); } } } // 写入文件 FileOutputStream outputStream = new FileOutputStream(filePath); workbook.write(outputStream); outputStream.close(); } } ``` 使用示例: ``` List userList = new ArrayList<>(); userList.add(new User("张三", 18, "男")); userList.add(new User("李四", 20, "女")); ExcelExportUtil.export(userList, "D:/user.xls"); ``` 其中,User类为需要导出的对象类,包含name、age和gender三个属性。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复