簡體   English   中英

Java僅打印數據的最后一個單元格

[英]Java prints only last cell of data

我正在嘗試從csv中讀取內容並將其打印到excel文件中。 到目前為止,我有這個,但它只將csv的最后一個值打印到excel文件的第一個單元格中。 我嘗試使用列和行的增量,但我得到一個空指針異常錯誤。

int i=0;
int j=0;
int k=0;
int row=68;
int column=0;
String [] part={"052","064"};
try{
    //InputStream inp = new FileInputStream();
    //Workbook wb = WorkbookFactory.create(inp);
    Workbook wb = WorkbookFactory.create(new File("30_results_w_graphs.xls"));


    for (k=0; k<part.length; k++)
    {
        Sheet sheet = wb.getSheet(part[k]);
            Cell cell = null;
        Scanner scanner = new Scanner(new File(part[k]+".csv"));
        scanner.useDelimiter(",");


        while(scanner.hasNext()){
            cell=sheet.getRow(row).getCell(column);
            cell.setCellValue(scanner.next());
            //row++;
            //column++;
            }
        FileOutputStream fileOut = new FileOutputStream("30_results_U_w_graphs.xls");
        wb.write(fileOut);
        scanner.close();
    }

}

我相信它是一個嵌套的for循環來增加行和列,但即使以常規增量,我得到一個空指針異常。

我不知道您想要做什么,但此代碼顯示了使用Apache POI將CSV文件讀取到現有Excel文件中的一些基本步驟。 現有的工作表/行/單元格不會被刪除。

CSV文件如下所示:

12,14,18,21
82,19,18,44
9,4,31,12

將文件讀入以文件名命名的工作表:

    File excel = new File("/tmp/result.xls");

    //Open existing Excel file:
    Workbook wb = WorkbookFactory.create(excel);

    //Create a new Excel file:
    //Workbook wb = new HSSFWorkbook();

    //Read in CSV
    String name = "test";
    Sheet sheet = wb.getSheet(name);
    if (sheet == null) {
        sheet = wb.createSheet(name);
    }

    int rowCount = 0;
    Scanner scanner = new Scanner(new File("/tmp/" + name + ".csv"));
    while (scanner.hasNextLine()) {
        String[] rowData = scanner.nextLine().split(",");
        for (int col = 0; col < rowData.length; col++) {
            Row row = sheet.getRow(rowCount);
            if (row == null)
                row = sheet.createRow(rowCount);
            Cell cell = row.getCell(col);
            if (cell == null) {
                cell = row.createCell(col);
            }
            cell.setCellValue(rowData[col]);
        }
        rowCount++;
    }

    wb.write(new FileOutputStream(excel));
}

您不會增加rowcolumn 使用createRow(int row)createCell(int column)創建新單元格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM