Java 使用 Poi 导出 Excel 通用(二)

版权声明:转载请注明出处 https://blog.csdn.net/qq_40162735/article/details/84954687

上一篇: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();
	}

猜你喜欢

转载自blog.csdn.net/qq_40162735/article/details/84954687