springboot将list<Map>集合导出为,固定列名,将map的键和值作为两列内容,自动分配列宽的Excel文件
时间: 2023-07-15 07:14:58 浏览: 213
可以使用Apache POI来实现将List<Map>集合导出为Excel文件。
步骤如下:
1. 创建Excel工作簿和工作表。
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
```
2. 创建表头,并设置列宽。
```java
Row headerRow = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
int colNum = 0;
for (String key : dataList.get(0).keySet()) {
Cell cell = headerRow.createCell(colNum++);
cell.setCellValue(key);
cell.setCellStyle(headerStyle);
sheet.setColumnWidth(colNum, (key.length() + 4) * 256);
}
```
3. 填充数据。
```java
int rowNum = 1;
for (Map<String, Object> map : dataList) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (String key : map.keySet()) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(String.valueOf(map.get(key)));
}
}
```
4. 将工作簿写入输出流中。
```java
workbook.write(outputStream);
workbook.close();
```
完整代码示例:
```java
public void exportExcel(List<Map<String, Object>> dataList, OutputStream outputStream) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row headerRow = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
int colNum = 0;
for (String key : dataList.get(0).keySet()) {
Cell cell = headerRow.createCell(colNum++);
cell.setCellValue(key);
cell.setCellStyle(headerStyle);
sheet.setColumnWidth(colNum, (key.length() + 4) * 256);
}
int rowNum = 1;
for (Map<String, Object> map : dataList) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (String key : map.keySet()) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(String.valueOf(map.get(key)));
}
}
workbook.write(outputStream);
workbook.close();
}
```
阅读全文