简体   繁体   中英

How can I read .xlsx and .xls files in Java?

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 ?

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

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.

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

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 .

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()); 
}

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();
            }
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM