获取异常(org.apache.poi.openxml4j.exception - 没有内容类型[M1.13])阅读使用Apache POI XLSX文件时? [英] Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

查看:22965
本文介绍了获取异常(org.apache.poi.openxml4j.exception - 没有内容类型[M1.13])阅读使用Apache POI XLSX文件时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Apache POI(XSSF API)读取XLSX file.when我试图读取file.i得到了以下错误:

i'm using Apache POI(XSSF API) for reading xlsx file.when i tried to read file.i got the following error:

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

code:

public class ReadXLSX
{
private String filepath;
private XSSFWorkbook workbook;
private static Logger logger=null;
private  InputStream resourceAsStream;

public ReadXLSX(String FilePath)
{
    logger=LoggerFactory.getLogger("ReadXLSX");
    this.filepath=FilePath;
    resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}

public ReadXLSX(InputStream fileStream)
{ 
    logger=LoggerFactory.getLogger("ReadXLSX");
    this.resourceAsStream=fileStream;
}
private void loadFile() throws FileNotFoundException, NullObjectFoundException
{
    if(resourceAsStream==null)
        throw new FileNotFoundException("Unable to locate give file..");
    else
    {
        try
        {
           workbook = new XSSFWorkbook(resourceAsStream);
        }
        catch(IOException ex)
        {
        }
    }
}// end loadxlsFile

public String[] getSheetsName()
{
   int totalsheet=0;int i=0;
   String[] sheetName=null;

    try {
        loadFile();
        totalsheet=workbook.getNumberOfSheets();
        sheetName=new String[totalsheet];
        while(i<totalsheet)
        {
           sheetName[i]=workbook.getSheetName(i);
           i++;
        }

    } catch (FileNotFoundException ex) {
       logger.error(ex);
    } catch (NullObjectFoundException ex) {
          logger.error(ex);
    }

   return sheetName;
}


public int[] getSheetsIndex()
{
   int totalsheet=0;int i=0;
   int[] sheetIndex=null;
    String[] sheetname=getSheetsName();
    try {
        loadFile();
        totalsheet=workbook.getNumberOfSheets();
        sheetIndex=new int[totalsheet];
        while(i<totalsheet)
        {
           sheetIndex[i]=workbook.getSheetIndex(sheetname[i]);
           i++;
        }

    } catch (FileNotFoundException ex) {
       logger.error(ex);
    } catch (NullObjectFoundException ex) {
          logger.error(ex);
    }

   return  sheetIndex;
}


private boolean validateIndex(int index)
{    
    if(index < getSheetsIndex().length && index >=0)
         return true;
    else
         return false;
}


public int getNumberOfSheet()
{
    int totalsheet=0;
    try {
        loadFile();
        totalsheet=workbook.getNumberOfSheets();

    } catch (FileNotFoundException ex) {
         logger.error(ex.getMessage());
    } catch (NullObjectFoundException ex) {
         logger.error(ex.getMessage());
    }

    return totalsheet;
    }

public int getNumberOfColumns(int SheetIndex)
{
    int NO_OF_Column=0;XSSFCell cell = null;
    XSSFSheet sheet=null;
            try {
                loadFile();  //load give Excel
                if(validateIndex(SheetIndex))
                {
                    sheet  = workbook.getSheetAt(SheetIndex);
                    Iterator rowIter = sheet.rowIterator();
                    XSSFRow firstRow = (XSSFRow) rowIter.next();
                    Iterator cellIter = firstRow.cellIterator();
                    while(cellIter.hasNext())
                    {
                          cell = (XSSFCell) cellIter.next();
                          NO_OF_Column++;
                    }
                }
                else
                    throw new InvalidSheetIndexException("Invalid sheet index.");
            } catch (Exception ex) {
                logger.error(ex.getMessage());

            }

    return NO_OF_Column;
}


public int getNumberOfRows(int SheetIndex)
{
        int NO_OF_ROW=0; XSSFSheet sheet=null;

        try {
                loadFile();  //load give Excel
               if(validateIndex(SheetIndex))
               {
                 sheet  = workbook.getSheetAt(SheetIndex);
                 NO_OF_ROW = sheet.getLastRowNum();
               }
               else
                    throw new InvalidSheetIndexException("Invalid sheet index.");
            } catch (Exception ex) {
                logger.error(ex);}

    return NO_OF_ROW;
}



 public String[] getSheetHeader(int SheetIndex)
{
            int noOfColumns = 0;XSSFCell cell = null; int i =0;
            String columns[] = null; XSSFSheet sheet=null;

            try {
                    loadFile();  //load give Excel
                    if(validateIndex(SheetIndex))
                    {
                     sheet  = workbook.getSheetAt(SheetIndex);
                     noOfColumns = getNumberOfColumns(SheetIndex);
                     columns = new String[noOfColumns];
                     Iterator rowIter = sheet.rowIterator();
                     XSSFRow Row = (XSSFRow) rowIter.next();
                     Iterator cellIter = Row.cellIterator();

                     while(cellIter.hasNext())
                     {
                        cell  = (XSSFCell) cellIter.next();
                        columns[i] = cell.getStringCellValue();
                        i++;
                     }
                  }
                    else
                         throw new InvalidSheetIndexException("Invalid sheet index.");
                }

                 catch (Exception ex) {
                    logger.error(ex);}

            return columns;
}//end of method


 public String[][] getSheetData(int SheetIndex)
 {
    int noOfColumns = 0;XSSFRow row = null;
    XSSFCell cell = null;
    int i=0;int noOfRows=0;
    int j=0;
    String[][] data=null; XSSFSheet sheet=null;

    try {
                    loadFile();  //load give Excel
                    if(validateIndex(SheetIndex))
                    {
                            sheet  = workbook.getSheetAt(SheetIndex);
                            noOfColumns = getNumberOfColumns(SheetIndex);
                            noOfRows =getNumberOfRows(SheetIndex)+1;
                            data = new String[noOfRows][noOfColumns];
                            Iterator rowIter = sheet.rowIterator();
                            while(rowIter.hasNext())
                            {
                                row = (XSSFRow) rowIter.next();
                                Iterator cellIter = row.cellIterator();
                                j=0;
                                while(cellIter.hasNext())
                                {
                                    cell  = (XSSFCell) cellIter.next();
                                    if(cell.getCellType() == cell.CELL_TYPE_STRING)
                                    {
                                        data[i][j] = cell.getStringCellValue();
                                    }
                                    else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
                                    {
                                        if (HSSFDateUtil.isCellDateFormatted(cell)) 
                                        {
                                         String formatCellValue = new DataFormatter().formatCellValue(cell);
                                         data[i][j] =formatCellValue;
                                        }
                                        else 
                                        {  
                                          data[i][j] = Double.toString(cell.getNumericCellValue());
                                        }

                                    }
                                    else if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN)
                                    {
                                         data[i][j] = Boolean.toString(cell.getBooleanCellValue());
                                    }

                                    else if(cell.getCellType() == cell.CELL_TYPE_FORMULA)
                                    {
                                         data[i][j] = cell.getCellFormula().toString();
                                    }

                                    j++;
                                }

                                i++;
                            }   // outer while


                    }
                    else throw new InvalidSheetIndexException("Invalid sheet index.");


                } catch (Exception ex) {
                    logger.error(ex);}
        return data;
 }

 public String[][] getSheetData(int SheetIndex,int noOfRows)
 {
    int noOfColumns = 0;
    XSSFRow row = null;
    XSSFCell cell = null;
    int i=0;
    int j=0;
    String[][] data=null;
    XSSFSheet sheet=null;

    try {
                    loadFile();  //load give Excel

                  if(validateIndex(SheetIndex))
                  {
                            sheet  = workbook.getSheetAt(SheetIndex);
                             noOfColumns = getNumberOfColumns(SheetIndex);
                             data = new String[noOfRows][noOfColumns];
                            Iterator rowIter = sheet.rowIterator();
                            while(i<noOfRows)
                            {

                                row = (XSSFRow) rowIter.next();
                                Iterator cellIter = row.cellIterator();
                                j=0;
                                while(cellIter.hasNext())
                                {
                                    cell  = (XSSFCell) cellIter.next();
                                    if(cell.getCellType() == cell.CELL_TYPE_STRING)
                                    {
                                        data[i][j] = cell.getStringCellValue();
                                    }
                                    else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
                                    {
                                         if (HSSFDateUtil.isCellDateFormatted(cell)) 
                                        {
                                         String formatCellValue = new DataFormatter().formatCellValue(cell);
                                         data[i][j] =formatCellValue;
                                        }
                                        else 
                                        {  
                                          data[i][j] = Double.toString(cell.getNumericCellValue());
                                        }
                                    }

                                    j++;
                                }

                                i++;
                            }   // outer while
              }else  throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
       logger.error(ex);
    }

    return data;
 }

请帮我理清这个问题。

感谢

推荐答案

该错误是告诉你,POI找不到OOXML文件的核心部分,在这种情况下,内容类型的一部分​​。您的文件是不是有效的OOXML文件,更何况是一个有效的.xlsx文件。这虽然是一个有效的zip文件,否则,你已经得到了以前的错误

The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error

可以将Excel真的加载此文件?我希望它也不能,因为异常被赋予POI常规.zip文件最常用的触发!我怀疑你的文件是无效的,因此例外

Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception

更新:在Apache的POI 3.15(从Beta 1起),有这个问题的比较常见的原因更有益的一套异常的消息。现在,您会在这种情况下获得更多的描述性的异常,如:<一href=\"http://poi.apache.org/apidocs/org/apache/poi/openxml4j/exceptions/ODFNotOfficeXmlFileException.html\"相对=nofollow> ODFNotOfficeXmlFileException 和<一个href=\"http://poi.apache.org/apidocs/org/apache/poi/openxml4j/exceptions/OLE2NotOfficeXmlFileException.html\"相对=nofollow> OLE2NotOfficeXmlFileException 。这种原始形式应该只会出现,如果真的POI有没有线索,你已经给它什么,但知道它的破碎或无效的。

Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException. This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.

这篇关于获取异常(org.apache.poi.openxml4j.exception - 没有内容类型[M1.13])阅读使用Apache POI XLSX文件时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆