使用Apache PO API创建CSV文件



我需要在一些配置的基础上创建CSV文件。

例子
  1. 从配置主我们定义文件的头,所以在创建文件时使用这个头,并在每列中只显示这个头的值。

  2. 头文件可能会改变,所以基本上是动态创建csv文件。

在CSV中是可能的吗?

请帮帮我。

试试这样做。这是基于您正在提供一个包含JSONObjects的列表的假设。

private String generateCSVWithDynamicHeaders(List<JSONObject> listToPrint) throws Exception {
XSSFRow row = null;
try {
if (listToPrint.size() < 1) return "You sent an empty list";
//Convert set to list. Alternatively you can just use iterator and leave this as a set.
List<String> headers = new ArrayList<>(listToPrint.get(0).keySet());
//Set row number where the headings will start from
int rowNum = 1;
//Excel / CSV creation
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Dynamic CSV");
row = sheet.createRow(rowNum);
//Set headers here
for (int h = 0; h < headers.size(); h++) {
row.createCell(h).setCellValue(headers.get(h));
}
//Increment row number such that the header is not over written
rowNum += 1;
//Print values after headers are done
for (JSONObject object : listToPrint) {
//Create a new row per iteration
row = sheet.createRow(rowNum);
for (int h = 0; h < headers.size(); h++) {
row.createCell(h).setCellValue(object.getString(headers.get(h)));
}
rowNum += 1;
}
String fileName = "Dynamic Sheet";
FileOutputStream outputStream = new FileOutputStream("./location-to-write-file-to/" + fileName + ".csv");
workbook.write(outputStream);
outputStream.close();
return "We are good";
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Unable to generate dymanic CSV");
}
}

最新更新