java两个集合导出excel
时间: 2024-01-18 16:43:46 浏览: 26
你可以使用 Apache POI 库来实现Java两个集合导出Excel。首先,你需要创建一个工作簿对象,然后创建一个工作表对象。接着,你可以使用 for 循环遍历每个集合中的元素,并将它们写入单元格中。最后,你需要将工作簿对象写入输出流中,以生成 Excel 文件。具体实现可以参考以下代码:
```java
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void export(List<Map<String, Object>> list1, List<Map<String, Object>> list2, String fileName) {
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream outputStream = new FileOutputStream(fileName)) {
Sheet sheet = workbook.createSheet("Sheet1");
// Write header row
Row row = sheet.createRow(0);
int columnCount = 0;
for (String key : list1.get(0).keySet()) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(key);
}
for (String key : list2.get(0).keySet()) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(key);
}
// Write data rows
int rowCount = 1;
for (Map<String, Object> map1 : list1) {
row = sheet.createRow(rowCount++);
columnCount = 0;
for (Object value : map1.values()) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(value.toString());
}
for (Map<String, Object> map2 : list2) {
row = sheet.createRow(rowCount++);
columnCount = list1.get(0).size();
for (Object value : map2.values()) {
Cell cell = row.createCell(columnCount++);
cell.setCellValue(value.toString());
}
}
}
// Resize columns to fit content
for (int i = 0; i < columnCount; i++) {
sheet.autoSizeColumn(i);
}
// Write workbook to output stream
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
你可以将两个集合作为参数传递给 `export` 方法,并指定要导出的 Excel 文件的名称。这个方法会将两个集合的数据写入同一个工作表中。注意,这个方法只支持导出 xlsx 格式的 Excel 文件。