确定Apache POI中是否需要HSSF或XSSF的最佳方法是什么?

时间:2016-02-09 15:26:49

标签: java excel apache-poi

我为Microsoft Excel文件实现上传服务,无法确定上传的文件类型。有时用户上传包含xlsx内容的xls扩展名的文件。 要解析我使用Apache Poi的文件,目前我首先尝试将上传的文件解析为HSSFWorkbook,如果我遇到异常,那么我尝试创建一个XSSFWorkbook。

有没有更智能的方法来检测需要哪个版本?

/** should parse the uploaded file */
private void handleUpload(File file) {
  Workbook wb = tryToHandleHSSF(file);
  if (wb==null)
    wb = tryToHandleXSSF(file);
  if (wb!=null) {
    // ... do the parsing stuff
  }
}

/** helper for HSSF */
private Workbook tryToHandleHSSF(File file) {
  try {
    return new HSSFWorkbook(new FileInputStream(file));
  }
  catch(Exception e) {
    return null;
  }
}

/** helper for XSSF */
private Workbook tryToHandleXSSF(File file) {
  Workbook workbook;
  try {
    InputStream fin = new FileInputStream(file);
    BufferedInputStream in = new BufferedInputStream(fin);
    try {
        if (POIFSFileSystem.hasPOIFSHeader(in)) {
            // if the file is encrypted
            POIFSFileSystem fs = new POIFSFileSystem(in);
            EncryptionInfo info = new EncryptionInfo(fs);
            Decryptor d = Decryptor.getInstance(info);
            d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
            workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook(d.getDataStream(fs));
        }
        else
            return new org.apache.poi.xssf.usermodel.XSSFWorkbook(in);
    }
    finally {
        in.close();
    }
  }
  catch(Exception e) {
    return null;
  }
}

1 个答案:

答案 0 :(得分:8)

您可以使用可以同时处理XSSF和HSSF工作簿的SS Usermodel。

要以类型无关的方式从文件加载工作簿,您可以使用WorkbookFactory中的create方法。

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;

...
...

// SS Workbook object
Workbook workbook;

// Handles both XSSF and HSSF automatically
workbook = WorkbookFactory.create(new FileInputStream(file)); 

//Do your parsing using the workbook object