如何在 Java 中读取 .xlsx 和 .xls 文件?

发布于 2024-10-12 12:32:55 字数 74 浏览 2 评论 0原文

你好 我想读取 xlsx 文件或 xls 文件,无论它是什么。 XSSF可以支持xls文件吗?或者我需要为这两种文件编写单独的代码吗?

hi
i want to read xlsx file or xls file what ever it is. can XSSF support xls file ? or do i need to write the separate code for both kind of files ?

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

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

发布评论

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

评论(6

赠佳期 2024-10-19 12:32:56

将其用于 xls 和 xlsx

Workbook wb_xssf; //Declare XSSF WorkBook 
Workbook wb_hssf; //Declare HSSF WorkBook 
Sheet sheet=null; //sheet can be used as common for XSSF and HSSF WorkBook 

if(fileBean.getFileExt().equalsIgnoreCase("xls")){
    wb_hssf = new HSSFWorkbook();
    sheet = wb_hssf.getSheetAt(0);
}else if (fileBean.getFileExt().equalsIgnoreCase("xlsx")){
    wb_xssf = new XSSFWorkbook(fileBean.getFileInput());      
    sheet = wb_xssf.getSheetAt(0);                                                          
}

use this for xls and xlsx

Workbook wb_xssf; //Declare XSSF WorkBook 
Workbook wb_hssf; //Declare HSSF WorkBook 
Sheet sheet=null; //sheet can be used as common for XSSF and HSSF WorkBook 

if(fileBean.getFileExt().equalsIgnoreCase("xls")){
    wb_hssf = new HSSFWorkbook();
    sheet = wb_hssf.getSheetAt(0);
}else if (fileBean.getFileExt().equalsIgnoreCase("xlsx")){
    wb_xssf = new XSSFWorkbook(fileBean.getFileInput());      
    sheet = wb_xssf.getSheetAt(0);                                                          
}
巾帼英雄 2024-10-19 12:32:56

您可以对 xlsx 文件尝试此操作:

首先,您需要下载以下 jar:

  • dom4j-2.1.0.jar
  • poi-3.17.jar
  • poi-ooxml-3.17.jar
  • commons-collections4-4.1.jar
  • xmlbeans-2.3.0.jar

其次,在您的工作区中添加以下导入:

import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

第三,开始构建您的方法,例如用于读取:

public void ReadExcelFiles(String pathxlsx,javax.swing.JTable jtable) throws IOException{
    //String nameSheet;
    File file = new File(pathxlsx);
    FileInputStream fis = new FileInputStream(file);
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    // nameSheet=wb.getSheetName(0);
    //XSSFSheet sh = wb.getSheet(nameSheet);
    XSSFSheet sh = wb.getSheetAt(0);
    System.out.println(sh.getLastRowNum());
    System.out.println("Name: "+sh.getSheetName()); 
    Row row = sh.getRow(6);

    System.out.println(row.getRowNum());
    System.out.println("columna "+row.getCell(1).getStringCellValue());
    System.out.println("columna "+row.getCell(2).getStringCellValue());
    System.out.println("columna "+row.getCell(3).getStringCellValue());
    System.out.println("columna "+row.getCell(4).getStringCellValue());

    System.out.println("Val: "+sh.getRow(4).getCell(6).getStringCellValue()); 
}

You can try this for xlsx files:

Firstly, you need the following jar downloads:

  • dom4j-2.1.0.jar
  • poi-3.17.jar
  • poi-ooxml-3.17.jar
  • commons-collections4-4.1.jar
  • xmlbeans-2.3.0.jar

Secondly, add the following imports in your workspace:

import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Thirdly, begin building your method, for example for read use this:

public void ReadExcelFiles(String pathxlsx,javax.swing.JTable jtable) throws IOException{
    //String nameSheet;
    File file = new File(pathxlsx);
    FileInputStream fis = new FileInputStream(file);
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    // nameSheet=wb.getSheetName(0);
    //XSSFSheet sh = wb.getSheet(nameSheet);
    XSSFSheet sh = wb.getSheetAt(0);
    System.out.println(sh.getLastRowNum());
    System.out.println("Name: "+sh.getSheetName()); 
    Row row = sh.getRow(6);

    System.out.println(row.getRowNum());
    System.out.println("columna "+row.getCell(1).getStringCellValue());
    System.out.println("columna "+row.getCell(2).getStringCellValue());
    System.out.println("columna "+row.getCell(3).getStringCellValue());
    System.out.println("columna "+row.getCell(4).getStringCellValue());

    System.out.println("Val: "+sh.getRow(4).getCell(6).getStringCellValue()); 
}
指尖上得阳光 2024-10-19 12:32:56

您可以使用以下代码并更改它(取决于您的需要):

public void parseXLSX() {

    String pathToXLSX = "file.xlsx";
    File file = new File(pathToXLSX);

    FileInputStream in = null;

    try {
        in = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet sheet = workbook.getSheetAt(i);
            int rowNumber = sheet.getLastRowNum() + 1;
            for (int j = 1; j < rowNumber; j++) {
                Iterator it = sheet.getRow(j).cellIterator();
                while (it.hasNext()) {
                    System.out.println(it.next().toString());
                }
            }
        }
    } catch (IOException ex) {
        ex.getMessage();
        ex.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                ex.getMessage();
                ex.printStackTrace();
            }
        }
    }

}

You can use the following code and change it (depends on your needs):

public void parseXLSX() {

    String pathToXLSX = "file.xlsx";
    File file = new File(pathToXLSX);

    FileInputStream in = null;

    try {
        in = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet sheet = workbook.getSheetAt(i);
            int rowNumber = sheet.getLastRowNum() + 1;
            for (int j = 1; j < rowNumber; j++) {
                Iterator it = sheet.getRow(j).cellIterator();
                while (it.hasNext()) {
                    System.out.println(it.next().toString());
                }
            }
        }
    } catch (IOException ex) {
        ex.getMessage();
        ex.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                ex.getMessage();
                ex.printStackTrace();
            }
        }
    }

}

七秒鱼° 2024-10-19 12:32:55

是的,您可以使用 Apache POI 读取和写入 xlsx 和 xls 文件。

Yes, you can use Apache POI to read and write xlsx and xls files.

知足的幸福 2024-10-19 12:32:55

如果您希望代码同时适用于两者,则必须使用 org.apache.poi.ss 包。创建此包是为了统一 XSSF 和 HSSF。

If you want your code to work for both, you'll have to use the org.apache.poi.ss package. This package has been created to unify XSSF and HSSF.

完美的未来在梦里 2024-10-19 12:32:55

对于我的一个项目,我创建了一个基本实用程序,它使用 Apache POI 和 OpenCSV,并且可以读取 xlsx、xls 和 csv 文件。

给定一个转换器,它可以将行转换为对象,如下所示:

RowConverter<Country> converter = (row) -> new Country(row[0], row[1]);

ExcelReader<Country> reader = ExcelReader.builder(Country.class)
     .converter(converter)
     .withHeader()
     .csvDelimiter(';')
     .sheets(1)
     .build();

List<Country> list;
list = reader.read("CountryCodes.xlsx");
list = reader.read("CountryCodes.xls");
list = reader.read("CountryCodes.csv");

您可以在 github 上找到该项目。

For one of my projects I have created a basic utility that uses Apache POI and OpenCSV and can read both xlsx, xls and csv files.

Given a converter it can convert rows to objects, like this:

RowConverter<Country> converter = (row) -> new Country(row[0], row[1]);

ExcelReader<Country> reader = ExcelReader.builder(Country.class)
     .converter(converter)
     .withHeader()
     .csvDelimiter(';')
     .sheets(1)
     .build();

List<Country> list;
list = reader.read("CountryCodes.xlsx");
list = reader.read("CountryCodes.xls");
list = reader.read("CountryCodes.csv");

You may find the project on github.

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