【发布时间】:2015-07-21 03:07:13
【问题描述】:
PersonDAO.java:
public List<Map<String, Object>> searchPersons(Person person)
String sql = "SELECT * FROM PERSON";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
return result;
}
如何将result中的数据转换成excel表格下载。
尝试使用 Apache POI:
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Person Detail");
Object[][] persons = {
{"PersonNAmeA", 1001},
{"PersonNAmeB", 1002},
{"PersonNAmeC", 1003},
};
int rowCount = 0;
for (Object[] person : persona) {
Row row = sheet.createRow(++rowCount);
int columnCount = 0;
for (Object field : person) {
Cell cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try (FileOutputStream outputStream = new FileOutputStream("PersonDetail.xlsx")) {
workbook.write(outputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
没有错误,但尚未创建 PersonDetail.xlsx。代码中可能有什么问题。
任何人都可以帮助解决这个问题。 谢谢
【问题讨论】:
-
如何将结果集写入平面文件,例如CSV 文件?不需要 API。 Excel 无论如何都可以将文本转换为列
-
@jmcg。感谢您的建议。我没试过,只是写入一个csv文件也会以Excel文件打开?
-
是的,Excel 可以打开一个 csv 文件。然后,您可以使用 excel 的文本到列功能将每个数据排列到相应的列中。看看这个链接superuser.com/questions/407082/…
-
谢谢。我正在尝试使用 apache poi,并且可以继续到现在。我也会试试这个。
标签: java sql excel oracle spring-boot