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