如何在java中读取Excel(.xlsx)文件?

rav*_*i_s 5 java excel android apache-poi

我正在尝试使用 Java从给定.xlsx文件中读取数据。

在此输入图像描述

我的读取文件的代码如下:

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

        FileInputStream file = new FileInputStream(new File("E:\\test1.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet test = workbook.getSheetAt(0);

        student emp = new student();
        Iterator<Row> itr = test.iterator();
        itr.next();
        while(itr.hasNext()){
               Row row = itr.next();
               emp.reedData(row);
               System.out.println(id+","+name+","+options);
        }
Run Code Online (Sandbox Code Playgroud)

方法如下:

void reedData(Row row){
    id= row.getCell(0).toString();
    name= row.getCell(1).toString();
    options= row.getCell(2).toString();
}
Run Code Online (Sandbox Code Playgroud)

但是,我得到这样的输出:

1.0,X,play game
,,sing song
2.0,Y,play game
,,sing song
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像这样,而不是上面的:

1.0,X,{play game,sing song}
2.0,Y,{play game,sing song}
Run Code Online (Sandbox Code Playgroud)

这个问题是因为我正在合并.xlsx文件中的两个单元格。

有什么建议吗?先感谢您..

Max*_*Max 0

您似乎正在使用 Apache POI。尝试将代码中的这 2 个单元格合并为:

test.addMergedRegion(1,2,0,0);
Run Code Online (Sandbox Code Playgroud)

或者:

sheet.addMergedRegion(new CellRangeAddress(1,2,0,0))
Run Code Online (Sandbox Code Playgroud)