import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListMapToExcel {
public static void main(String[] args) {
// 创建包含Map的List
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("Name", "Alice");
map1.put("Age", 30);
Map<String, Object> map2 = new HashMap<>();
map2.put("Name", "Bob");
map2.put("Age", 25);
list.add(map1);
list.add(map2);
// 创建Excel工作簿
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data");
// 创建标题行
Row headerRow = sheet.createRow(0);
List<String> headers = new ArrayList<>(list.get(0).keySet());
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers.get(i));
}
// 填充数据
int rowNum = 1;
for (Map<String, Object> dataMap : list) {
Row row = sheet.createRow(rowNum++);
for (int i = 0; i < headers.size(); i++) {
Cell cell = row.createCell(i);
Object value = dataMap.get(headers.get(i));
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
}
// 可以根据需要添加更多类型的处理
}
}
// 将工作簿写入文件
try (FileOutputStream outputStream = new FileOutputStream("ListMapData.xlsx")) {
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ListMapToExcel
最新推荐文章于 2024-09-04 11:14:53 发布