1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| private static void write(List<Map<String,String>> list, String[] headers, OutputStream out) { Workbook wb = new XSSFWorkbook(); "遍历数据集,把数据写入到wb对象"
Sheet sheet = wb.createSheet("员工表"); Row row = sheet.createRow(0); "表头" int cellindex=0; for (String head:headers){ Cell cell = row.createCell(cellindex); cell.setCellValue(head); cellindex++; }
"数据行" int rowIndex= 1; for(Map<String,String> map:list){ Row trow = sheet.createRow(rowIndex); for(int c=0;c<headers.length;c++){ Cell cell = trow.createCell(c); String key = headers[c]; String cellValue = map.get(key); cell.setCellValue(cellValue); } rowIndex++; }
try { wb.write(out); } catch (IOException e) { e.printStackTrace(); } }
"调用" public static void main(String[] args) throws FileNotFoundException { List<Map<String,String>> list = new ArrayList<>(); Map<String,String> map = new HashMap<>(); map.put("序号","1"); map.put("姓名","张三"); map.put("性别","男"); map.put("生日","2015-11-11"); list.add(map);
String path ="D:/aaa.xlsx"; OutputStream out = new FileOutputStream(path); String[] headers = {"序号","姓名","性别","生日"}; write(list,headers,out); }
|