`
jasonw68
  • 浏览: 149052 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

POI导出数据到Excel

    博客分类:
  • J2SE
阅读更多
public class ExportToExcel {

	/**
	 * 
	 * @param list
	 * @param fields
	 * @param values
	 * @param savePath
	 * @param sheetName
	 * @return
	 */
	public static String GenerateExcel(List<Map<String, Object>> list,
			String[] fields, String[] values, String savePath, String sheetName) {

		String flag = "false"; // 设置开关

		try {
			HSSFWorkbook wb = new HSSFWorkbook(); // 声明一个工作薄
			HSSFSheet sheet = wb.createSheet(sheetName);// 声明一个表

			HSSFRow row = null; // 声明行
			HSSFCell cell = null;// 声明单元

			// 创建表头,第一行为0
			row = sheet.createRow(0);

			for (int i = 0; i < values.length; i++) {

				cell = row.createCell(i); // 创建标题

				cell.setCellValue(values[i]);// 写入标题

				// System.out.println(entry.getValue());
			}

			Map<String, Object> map = null;

			// 写入标题和内容
			for (int rowindex = 0; rowindex < list.size(); rowindex++) {

				row = sheet.createRow(rowindex + 1); // 从第二行开始

				map = list.get(rowindex); // 集合数据写入对象

				for (int i = 0; i < fields.length; i++) {

					cell = row.createCell(i);// 创建内容

					cell.setCellValue((String)map.get(fields[i])); // 设置单元格的值

					// System.out.println(entry.getKey());
				}

			}

			// 存入文件
			FileOutputStream out = new FileOutputStream(savePath);
			wb.write(out);
			out.close();

			flag = "true";

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return flag;
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics