简体   繁体   English

使用JSON数组中的Apache POI编写Excel工作表

[英]Writing Excel sheet using Apache POI from a json array

I'm trying to pull 5 pieces of json data and write them to an excel sheet. 我正在尝试提取5条json数据并将其写入Excel工作表。 I'm converting the data to a jsonarray and then writing to excel using POI. 我将数据转换为jsonarray,然后使用POI写入excel。 For some reason, the program is currently only writing the 5th data piece to the first row, and not doing anything with the others. 由于某种原因,该程序当前仅将第5个数据段写入第一行,而对其他行不做任何操作。 It should be looping through all 5 and putting each in the row it corresponds with. 它应该遍历所有5个,并将每个放置在与之对应的行中。 Any ideas? 有任何想法吗?

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

        }
}

It looks like you're overwriting the file with each row. 看来您要覆盖每一行的文件。 Try putting the write outside the loop. 尝试将写操作置于循环之外。

Also, get rid of the rowCount variable. 此外,摆脱rowCount变量。 You want to use your rowNumber variable there. 您想在那里使用rowNumber变量。

Finally, I think you're only looping 4 times. 最后,我认为您只循环了4次。 (You indicate you want 5 in your question.) (您表示想在问题中输入5。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM