正确读取 excel 行

reading excel rows properly

我正在尝试从 .xlsx 文件中读取多行数据。控制台中的输出显示所有值一个接一个地显示。

问题是它们没有以 table 的方式显示,因为它们在源 excel sheet 中显示。

我的 excel 文件是 .xlsx,所以我使用 XSSF POI api 进行编码。 它包含两列(姓名和分数),总共 5 行。

控制台输出如下所示

Name
Score
TOM
1
DICK
2
HARRY
3
JERRY
4

我希望它打印成这样:

Name            Score
TOM              1
DICK             2
HARRY            3
JERRY            4

代码:

package gmailExcel;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadXl {

    public static void main(String[] args) throws IOException {

 // Locate xl file.
            FileInputStream fis = new FileInputStream
            ("File location on local host");

 // Load file, workbook and sheet.
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet ws = wb.getSheet("sheetName");


 // Declare row and cell variable.      
            XSSFRow row;
            XSSFCell cells;

 // Get row and column count.
            int rowCount = ws.getLastRowNum();
            int colCount = ws.getRow(0).getLastCellNum();

 // Iterate over rows and columns.
            for(int r = 0; r < rowCount; r++) {
                row = ws.getRow(r);

                    for(int c = 0; c < colCount; c++) {
                         cells  = row.getCell(c);



 // Output the values from Excel sheet.                 
            String cellval = cells.toString();
            System.out.println(cellval);
                        }

                    }

                }
            }

问题出在您的嵌套 for 循环中。在每次迭代中,您都在其后打印一个换行符的值。你想要做的是仅在我假设的第二列中打印单元格后才打印换行符。

这可以通过像这样在嵌套循环外打印换行符来实现:

for (int r = 0; r < rowCount; r++) {
    for (int c = 0; c < colCount; c++) {
        cells = row.getCell(c);
        String cellval = cells.toString();
        System.out.print(" | " + cellval);   //New line IS NOT printed
    }
    System.out.println(" |");                //New line IS printed
}