POIデータのExcelへのエクスポート

1758 ワード

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;
	}

}