Apache POI XSSF 读取 Excel 文件

发布于 2024-11-07 09:59:43 字数 468 浏览 4 评论 0原文

我只是有一个关于如何使用 Apache 的 XSSF 格式读取 xlsx 文件的快速问题。

现在我的代码如下所示:

InputStream fs = new FileInputStream(filename);   // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs);           // (2)
XSSFSheet sheet = wb.getSheetAt(0);               // (3)

...导入了所有相关内容。我的问题是,当我点击运行时,它卡在第 (2) 行,几乎陷入无限循环。 filename 只是一个字符串。

如果有人能给我一些关于如何解决这个问题的示例代码,我将非常感激。我现在想要的只是从 xlsx 文件中读取单个单元格;我对 xls 文件使用 HSSF,没有任何问题。

感谢您的帮助, 安德鲁

I just have a quick question about how to read in an xlsx file using the XSSF format from Apache.

Right now my code looks like this:

InputStream fs = new FileInputStream(filename);   // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs);           // (2)
XSSFSheet sheet = wb.getSheetAt(0);               // (3)

...with all the relevant things imported. My problem is that when I hit run, it gets stuck at line (2), in almost an infinite loop. filename is just a string.

If anybody could give me some sample code on how to fix this I would really appreciate it. All i want right now is to read in a single cell from an xlsx file; I was using HSSF for xls files and had no problems.

Thanks for your help,
Andrew

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

糖粟与秋泊 2024-11-14 09:59:43

我相信这会回答您的问题: http://poi.apache.org/ Spreadsheet/quick-guide.html#ReadWriteWorkbook

简而言之,您的代码应如下所示:

InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);

I bealive that this will answer your questions: http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook

In short, your code should look like this:

InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
昔日梦未散 2024-11-14 09:59:43
InputStream inp = null;
        try {
            inp = new FileInputStream("E:/sample_poi.xls");

            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Header header = sheet.getHeader();

            int rowsCount = sheet.getLastRowNum();
            System.out.println("Total Number of Rows: " + (rowsCount + 1));
            for (int i = 0; i <= rowsCount; i++) {
                Row row = sheet.getRow(i);
                int colCounts = row.getLastCellNum();
                System.out.println("Total Number of Cols: " + colCounts);
                for (int j = 0; j < colCounts; j++) {
                    Cell cell = row.getCell(j);
                    System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
                }
            }

        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inp.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
InputStream inp = null;
        try {
            inp = new FileInputStream("E:/sample_poi.xls");

            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Header header = sheet.getHeader();

            int rowsCount = sheet.getLastRowNum();
            System.out.println("Total Number of Rows: " + (rowsCount + 1));
            for (int i = 0; i <= rowsCount; i++) {
                Row row = sheet.getRow(i);
                int colCounts = row.getLastCellNum();
                System.out.println("Total Number of Cols: " + colCounts);
                for (int j = 0; j < colCounts; j++) {
                    Cell cell = row.getCell(j);
                    System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
                }
            }

        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inp.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
夜无邪 2024-11-14 09:59:43

为什么要将文件分解为输入流? XSSFWorkbook 有一个构造函数,它仅将路径作为字符串。只需对字符串的路径进行硬编码即可。创建工作簿后,您可以从中创建 XSSFSheets。然后是 XSSFCells,它最终将允许您读取单个单元格的内容(单元格本质上基于 x,y 位置)

Why are you breaking the file into an InputStream? XSSFWorkbook has a constructor that simply takes the path as a String. Just hard code the path of the string in. Once you create the workbook you can create XSSFSheets from that. Then XSSFCells, which will then finally allow you to read the contents of a single cell (cells are based on x,y locations, essentially)

呆头 2024-11-14 09:59:43

您可以尝试以下操作。

private static void readXLSX(String path) throws IOException {
    File myFile = new File(path);
    FileInputStream fis = new FileInputStream(myFile);

    // Finds the workbook instance for XLSX file
    XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);

    // Return first sheet from the XLSX workbook
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);

    // Get iterator to all the rows in current sheet
    Iterator<Row> rowIterator = mySheet.iterator();

    // Traversing over each row of XLSX file
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        // For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                break;
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue() + "\t");
                break;
            default :

            }
        }
        System.out.println("");
    }
}

You can try the following.

private static void readXLSX(String path) throws IOException {
    File myFile = new File(path);
    FileInputStream fis = new FileInputStream(myFile);

    // Finds the workbook instance for XLSX file
    XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);

    // Return first sheet from the XLSX workbook
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);

    // Get iterator to all the rows in current sheet
    Iterator<Row> rowIterator = mySheet.iterator();

    // Traversing over each row of XLSX file
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        // For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                break;
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue() + "\t");
                break;
            default :

            }
        }
        System.out.println("");
    }
}
烛影斜 2024-11-14 09:59:43

这工作正常:尝试一下

File filename = new File("E:/Test.xlsx");
FileInputStream isr= new FileInputStream(filename);

Workbook book1 = new XSSFWorkbook(isr);
Sheet sheet = book1.getSheetAt(0);  
Iterator<Row> rowItr = sheet.rowIterator();

this works fine: try it

File filename = new File("E:/Test.xlsx");
FileInputStream isr= new FileInputStream(filename);

Workbook book1 = new XSSFWorkbook(isr);
Sheet sheet = book1.getSheetAt(0);  
Iterator<Row> rowItr = sheet.rowIterator();
2024-11-14 09:59:43
public class ExcelReader{
   public String path;
   public static FileInputStream fis;

   public ExcelReader(){
      System.out.println("hello");
   }

   public ExcelReader(String path){
      this.path=path;
      fis=new FileInputStream(path);
      XSSFWorkbook workbook=new XSSFWorkbook(fis);
      XSSFSheet sheet=workbook.getSheet("Sheet1");//name of the sheet
      System.out.println(sheet.getSheetName());
      System.out.println(sheet.getLastRowNum());
      System.out.println(sheet.getRow(2).getCell(3));
  }
  public static void main(String[] args) throws IOException {
      ExcelReader excel=new ExcelReader("path of xlsx");
  }
}
public class ExcelReader{
   public String path;
   public static FileInputStream fis;

   public ExcelReader(){
      System.out.println("hello");
   }

   public ExcelReader(String path){
      this.path=path;
      fis=new FileInputStream(path);
      XSSFWorkbook workbook=new XSSFWorkbook(fis);
      XSSFSheet sheet=workbook.getSheet("Sheet1");//name of the sheet
      System.out.println(sheet.getSheetName());
      System.out.println(sheet.getLastRowNum());
      System.out.println(sheet.getRow(2).getCell(3));
  }
  public static void main(String[] args) throws IOException {
      ExcelReader excel=new ExcelReader("path of xlsx");
  }
}
诗笺 2024-11-14 09:59:43

我有同样的错误,我刚刚用相同的版本更新了 pom 依赖项。它起作用了。

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>

I have the same error, I have just updated the pom dependencies with the same version. It worked.

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>
把人绕傻吧 2024-11-14 09:59:43
// Load sheet- Here we are loading first sheet only
XSSFSheet xlSheet = wb.getSheetAt(0);

这里的代码仅识别第一张工作表 - 在我的 Excel 中存在多个工作表,因此面临将 sheet2 更改为 sheet1(getSheetAt(0)) 的问题...

// Load sheet- Here we are loading first sheet only
XSSFSheet xlSheet = wb.getSheetAt(0);

Here code recognizing only first sheet - In my Excel multiple sheets are there so facing problem to change sheet2 to sheet1(getSheetAt(0))...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文