若依的java架构导出excel,对象属性为list<map>怎么办
时间: 2024-01-21 11:19:53 浏览: 28
如果你需要将一个对象属性为`List<Map<String, Object>>`的Java对象导出为Excel文件,可以使用Apache POI来实现。
下面是一个简单的示例代码:
```
public void exportToExcel(List<Map<String, Object>> dataList, String filePath) throws IOException {
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook();
// 创建工作表对象
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头行
Row headerRow = sheet.createRow(0);
// 获取第一个Map对象的所有key作为表头
Map<String, Object> firstData = dataList.get(0);
int columnIndex = 0;
for (String key : firstData.keySet()) {
Cell headerCell = headerRow.createCell(columnIndex);
headerCell.setCellValue(key);
columnIndex++;
}
// 写入数据行
int rowIndex = 1;
for (Map<String, Object> data : dataList) {
Row dataRow = sheet.createRow(rowIndex);
columnIndex = 0;
for (String key : firstData.keySet()) {
Cell dataCell = dataRow.createCell(columnIndex);
dataCell.setCellValue(data.get(key).toString());
columnIndex++;
}
rowIndex++;
}
// 保存工作簿到文件
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.close();
}
```
使用该方法,你可以将`List<Map<String, Object>>`类型的数据写入Excel文件,并保存到指定路径。你只需要将`dataList`替换为你的数据集合,`filePath`替换为你要保存的文件路径即可。