从文件读取时,Apache POI会抛出编码错误,但不会从Stream中抛出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从文件读取时,Apache POI会抛出编码错误,但不会从Stream中抛出相关的知识,希望对你有一定的参考价值。

通过Java(7)中的Apache POI(3.17)加载特定的Excel(XLSX)文件时,我得到一个关于编码的例外(org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence)。这似乎是在读取sharedStrings.xml文件时(nb此文件以UTF8编码)。

但是,如果我通过InputStream而不是File加载文件,则文件正确加载。在任何情况下,我(或我都可以)指定编码。我知道从InputStream加载不是最佳的,我很想避免这种情况。

我写了一个小例子来突出我的问题,虽然不幸的是我不能分享有问题的文件:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.MessageFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class POIEncodingIssue
{
    public static void main(final String[] args) throws Exception
    {
        final File file = new File("path\to\my\file.xlsx"); //$NON-NLS-1$
        Workbook workbook = null;

        // This works
        System.out.println("Trying Stream based approach..."); //$NON-NLS-1$
        try (InputStream stream = new FileInputStream(file))
        {
            workbook = WorkbookFactory.create(stream);

            System.out.println(MessageFormat.format("Value was "{0}"", workbook.getSheetAt(0).getRow(0).getCell(0))); //$NON-NLS-1$
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (workbook != null)
            {
                workbook.close();
            }
        }

        // This doesn't
        System.out.println("Trying File based approach..."); //$NON-NLS-1$
        try
        {
            workbook = WorkbookFactory.create(file);

            System.out.println(MessageFormat.format("Value was "{0}"", workbook.getSheetAt(0).getRow(0).getCell(0))); //$NON-NLS-1$
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (workbook != null)
            {
                workbook.close();
            }
        }
    }
}

而产生的异常:

org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
    at org.apache.poi.POIXMLFactory.createDocumentPart(POIXMLFactory.java:63)
    at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:580)
    at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:165)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:270)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:266)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:226)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:205)
    at com.in2.excelreader_art.DAT3983Example.main(DAT3983Example.java:42)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:56)
    at org.apache.poi.POIXMLFactory.createDocumentPart(POIXMLFactory.java:60)
    ... 7 more
Caused by: java.io.IOException: Unable to parse xml bean
    at org.apache.poi.POIXMLTypeLoader.parse(POIXMLTypeLoader.java:166)
    at org.openxmlformats.schemas.spreadsheetml.x2006.main.SstDocument$Factory.parse(Unknown Source)
    at org.apache.poi.xssf.model.SharedStringsTable.readFrom(SharedStringsTable.java:119)
    at org.apache.poi.xssf.model.SharedStringsTable.<init>(SharedStringsTable.java:107)
    ... 13 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 5443012; Invalid byte 2 of 4-byte UTF-8 sequence.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
    at org.apache.poi.util.DocumentHelper.readDocument(DocumentHelper.java:140)
    at org.apache.poi.POIXMLTypeLoader.parse(POIXMLTypeLoader.java:163)
    ... 16 more
Caused by: org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence.
    at org.apache.xerces.impl.io.UTF8Reader.invalidByte(Unknown Source)
    at org.apache.xerces.impl.io.UTF8Reader.read(Unknown Source)
    at org.apache.xerces.impl.XMLEntityScanner.load(Unknown Source)
    at org.apache.xerces.impl.XMLEntityScanner.scanContent(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanContent(Unknown Source)
    ... 26 more
答案

促进对答案的评论

您似乎遇到了旧版Apache XML Beans中的错误。如果你升级到至少Apache XML Beans 3.0.1你会发现问题消失了。

理想情况下,您还要升级到至少Apache POI 4.0.0,这需要更新的xmlbeans,但这需要Java 8+。 XML Beans是向后兼容的,所以你可以坚持使用POI 3.17并且只需要升级xmlbeans(虽然很明显没有4中的POI修复!)

以上是关于从文件读取时,Apache POI会抛出编码错误,但不会从Stream中抛出的主要内容,如果未能解决你的问题,请参考以下文章

为啥 InputStreamReader 从 jar 读取时会抛出 NPE?

在 Apache Web 服务器中读取带有特殊字符的图像

为什么Apache poi的Workbook.close()方法将内容写入输入文件?

使用Apache Commons IO组件读取大文件

在使用 apache poi 从扩展名为 xlsx 的 Excel 文件中读取数据时,需要很长时间

服务器无法读取htaccess文件