Java Excel动态列 导出
时间: 2023-08-10 21:07:03 浏览: 152
Java中Excel导出操作
Java可以使用Apache POI库来操作Excel文件,实现动态列导出。下面是一个示例代码:
```java
public void exportExcel(List<Map<String, Object>> dataList, HttpServletResponse response) throws IOException {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头
Row headerRow = sheet.createRow(0);
List<String> headerList = new ArrayList<>();
for (Map.Entry<String, Object> entry : dataList.get(0).entrySet()) {
headerList.add(entry.getKey());
}
for (int i = 0; i < headerList.size(); i++) {
Cell headerCell = headerRow.createCell(i);
headerCell.setCellValue(headerList.get(i));
}
// 填充数据
int rowIndex = 1;
for (Map<String, Object> data : dataList) {
Row row = sheet.createRow(rowIndex++);
int columnIndex = 0;
for (Map.Entry<String, Object> entry : data.entrySet()) {
Cell cell = row.createCell(columnIndex++);
cell.setCellValue(entry.getValue().toString());
}
}
// 设置响应头信息
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=data.xlsx");
// 输出Excel文件
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
```
其中,`dataList`是一个包含多个Map的List,每个Map代表一行数据,Map的key为列名,value为对应的值。这样,我们就可以根据传入的数据动态地生成Excel文件了。
阅读全文