gpt4 book ai didi

java - 使用 Apache POI 从 json 数组编写 Excel 工作表

转载 作者:行者123 更新时间:2023-12-02 02:31:46 27 4
gpt4 key购买 nike

我正在尝试提取 5 条 json 数据并将它们写入 Excel 工作表。我将数据转换为 jsonarray,然后使用 POI 写入 Excel。由于某种原因,程序当前仅将第 5 个数据 block 写入第一行,而没有对其他数据 block 执行任何操作。它应该循环遍历所有 5 个并将每个放入与其对应的行中。有什么想法吗?

private void sendPost() {
int rowNumber = 1;

while (rowNumber < 5 ) {
try {
String id = censusIdValue(rowNumber);
String url = "https://www.broadbandmap.gov/broadbandmap/analyze/jun2014/summary/population/censusplace/ids/" + URLEncoder.encode(id, "UTF-8") + "?format=json";
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
InputStream is = response.getEntity().getContent();
String result = getStringFromInputStream(is);
JSONObject jsonObj = new JSONObject(result.toString());
JSONArray data = jsonObj.getJSONArray("Results");
int rowCount = 0;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("wow");

JSONObject rec = data.getJSONObject(0);
String geographyId = rec.getString("geographyId");
String strStatusType = rec.getString("geographyName");
int numberOfWirelineProvidersEquals0 = rec.getInt("numberOfWirelineProvidersEquals0");

XSSFRow row = sheet.createRow(rowCount++);
XSSFCell cell1 = row.createCell(1);
cell1.setCellValue(geographyId);
XSSFCell cell2 = row.createCell(2);
cell2.setCellValue(strStatusType);
XSSFCell cell3 = row.createCell(3);
cell3.setCellValue(numberOfWirelineProvidersEquals0);

try (FileOutputStream outputStream = new FileOutputStream("data.xlsx")) {
workbook.write(outputStream);
}


} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

rowNumber++;

}
}

最佳答案

看起来您正在用每一行覆盖文件。尝试将写入放在循环之外。

此外,删除 rowCount 变量。您想在那里使用您的 rowNumber 变量。

最后,我认为你只循环了 4 次。 (您在问题中表明您想要 5。)

关于java - 使用 Apache POI 从 json 数组编写 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46984477/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com