首页 > 代码库 > 使用POI解析Excel时,出现org.xml.sax.SAXParseException: duplicate attribute 'o:relid'的解决办法

使用POI解析Excel时,出现org.xml.sax.SAXParseException: duplicate attribute 'o:relid'的解决办法

1.使用org.apache.poi解析excle,.xlsx类型文件
InputStream is = new FileInputStream(strFileName);
XSSFWorkbook wb = new XSSFWorkbook(is);
出现异常如下:
org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:62)
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403)
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:408)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:183)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:73)
at ru.otr.core.Document.<init>(Document.java:21)
at ru.otr.EnergyLoader.main(EnergyLoader.java:175)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60)
... 7 more
Caused by: org.apache.xmlbeans.XmlException: error: duplicate attribute ‘o:relid‘
at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3511)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1277)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1264)
at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
at org.apache.xmlbeans.XmlObject$Factory.parse(XmlObject.java:688)
at org.apache.poi.xssf.usermodel.XSSFVMLDrawing.read(XSSFVMLDrawing.java:107)
at org.apache.poi.xssf.usermodel.XSSFVMLDrawing.<init>(XSSFVMLDrawing.java:102)
... 12 more
Caused by: org.xml.sax.SAXParseException: duplicate attribute ‘o:relid‘
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.reportFatalError(Piccolo.java:1038)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.parse(Piccolo.java:723)
at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3479)
... 18 more

解决办法有点复杂,请大家尝试;
 1 InputStream is = new FileInputStream(strFileName);
 2 OPCPackage pkg = OPCPackage.open(is);
 3 PackagePart p = null;
 4 for(PackagePart part:pkg.getParts()){
 5   if(part.getPartName().getName().equals("/xl/drawings/vmlDrawing1.vml")){
 6     p = part;
 7   }
 8 }
 9 if(p != null){
10   pkg.removePart(p);
11 }
12 XSSFWorkbook wb = new XSSFWorkbook(pkg);
1.使用OPCPackage解压读入的excel流,然后找到出错的那个part,例如/xl/drawings/vmlDrawing1.vml。
2.使用pkg.removePart(p)方法,remove掉就出错的part可以解决了。
3.不过目前只解决了自己遇到的问题,如果大家是其他的part有问题,需要测试一下remove掉后,XSSFWorkbook是否能够正确解析。


使用POI解析Excel时,出现org.xml.sax.SAXParseException: duplicate attribute 'o:relid'的解决办法