正确阅读excel行

时间:2016-02-25 00:24:33

标签: java automation xssf

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

问题是它们没有像源excel表中显示的那样显示在表格中。

我的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);
                        }

                    }

                }
            }

1 个答案:

答案 0 :(得分:0)

问题出在你的嵌套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
}