我试图拉出5张json数据并将它们写入excel表。我将数据转换为jsonarray,然后使用POI写入excel。出于某种原因,该程序目前只将第五个数据块写入第一行,而不对其他数据块执行任何操作。它应循环遍历所有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++;
}
}
答案 0 :(得分:2)
看起来你正在用每一行覆盖文件。尝试将写入放在循环之外。
另外,摆脱rowCount
变量。您想在那里使用rowNumber
变量。
最后,我认为你只是循环了4次。 (你的问题表明你想要5个。)