Java 使用 Poi 匯出 Excel 通用(二)
阿新 • • 發佈:2019-01-02
上一篇:Java 使用 Poi 匯入 Excel 通用(一)
/** * 檔案寫入excel * @param file 檔案 * @param list 資料來源 * @param sheetname 工作簿 * @throws IOException */ @SuppressWarnings("resource") public void exportExcel(File file,List<LinkedHashMap<String,Object>> list,String sheetname) throws IOException{ Workbook workbook = new XSSFWorkbook(FileUtils.openInputStream(file)); Sheet sheet = workbook.getSheet(sheetname); Row row = sheet.getRow(1); if (row == null) { row = sheet.createRow(1); } LinkedHashMap<String, Object> m =list.get(0); String [] title = new String[m.size()]; int v = 0; for(String key : m.keySet()){ title[v] = key; v++; } fos = new FileOutputStream(file); for (int i = 0; i < list.size(); i++) { row = sheet.createRow(i + 1); LinkedHashMap<String, Object> map = list.get(i); for (int j = 0; j < title.length; j++) { row.createCell((short) j).setCellValue(map.get(title[j]) + ""); } } workbook.write(fos); fos.flush(); fos.close(); }