添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Ask Question

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..");
           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);
    } 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]);
    } 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;
         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++;
                    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();
                    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();
                         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();
                                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;
                                          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();
                            }   // 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();
                                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;
                                          data[i][j] = Double.toString(cell.getNumericCellValue());
                            }   // outer while
              }else  throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
       logger.error(ex);
    return data;

please help me to sort out this problem.

Thanks

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

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

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.

I have the very same problem, and unfortunatelly Excel can open it without any trouble. I wonder if there is any part of the API to make a test on the file. – Andres Farias Jan 5, 2014 at 23:14 If you're sure it's a valid file, and not corrupt, your best bet is to open a bug in the POI Bugzilla issue tracker, and upload an example problematic file for people to examine – Gagravarr Jan 5, 2014 at 23:35 I get this error when trying to read an Excel file on Windows, when it was exported to Excel format from my Mac.. – user448787 Apr 23, 2015 at 8:47 @user448787 If you're sure it's a valid Excel .xlsx file, create a new bug in the Apache POI Bugzilla and upload the problematic file there – Gagravarr Apr 23, 2015 at 14:50 In my case, the file is indeed invalid. Nonetheless, is there a way to fix it programmatically? Since the excel files are generated by a third party, I do not have control ever it. – Mr. 14 Jul 20, 2015 at 11:25

Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....
static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";
public static void ReadExcel() {
InputStream inputStream = null;
   try {
        inputStream = new FileInputStream(new File(excelLoc));
        Workbook wb = WorkbookFactory.create(inputStream);
        int numberOfSheet = wb.getNumberOfSheets();
        for (int i = 0; i < numberOfSheet; i++) {
             Sheet sheet = wb.getSheetAt(i);
             //.... Customize your code here
             // To get sheet name, try -> sheet.getSheetName()
   } catch {}
                very well said @Wilts C, i had wasted a mere 1 hour on this excel file, the word corrupted of ur answer made me to open the excel windows itself. Then windows also said the same. Uffffff...
– DJphy
                May 28, 2015 at 6:01
                Very good example of POI usage. Usually the HSSF/XSSF abstraction solves all issues of above kind.
– Aram Paronikyan
                Jul 29, 2015 at 14:11
                I'm VERY SURE it's not! @Wilts - I opened the same file in Windows and it's all fine. The issue found when I reached the end of the data in the excel
– Shai Alon
                Dec 27, 2020 at 19:59
                Is there anything I can do about the password? I'm converting xlxs to txt, it works fine if the excel is not password protected.
– aaa
                Jul 7, 2021 at 2:24

I was using XSSFWorkbook to read .xls, which resulted in InvalidFormatException. I have to use a more generic Workbook and Sheet to make it work.

This post helped me solved my problem.

You might also see this error if you attempt to parse the same file twice from the same source.

I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.

To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.

Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
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);
    } 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]);
    } 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;
        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;
    @SuppressWarnings("unused")
    XSSFCell cell = null;
    XSSFSheet sheet = null;
    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            Iterator<Row> rowIter = sheet.rowIterator();
            XSSFRow firstRow = (XSSFRow) rowIter.next();
            Iterator<Cell> 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<Row> rowIter = sheet.rowIterator();
            XSSFRow Row = (XSSFRow) rowIter.next();
            Iterator<Cell> cellIter = Row.cellIterator();
            while (cellIter.hasNext()) {
                cell = (XSSFCell) cellIter.next();
                columns[i] = cell.getStringCellValue();
        } 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<Row> rowIter = sheet.rowIterator();
            while (rowIter.hasNext()) {
                row = (XSSFRow) rowIter.next();
                Iterator<Cell> 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();
            } // 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<Row> rowIter = sheet.rowIterator();
            while (i < noOfRows) {
                row = (XSSFRow) rowIter.next();
                Iterator<Cell> 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());
            } // outer while
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex);
    return data;

Created this little testcode:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
 * @param args
 * @throws FileNotFoundException 
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
    System.out.println(test.getSheetsName());
    System.out.println(test.getNumberOfSheet());

All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.

Cheers,

I get the same exception for .xls file, but after I open the file and save it as xlsx file , the below code works:

 try(InputStream is =file.getInputStream()){
      XSSFWorkbook workbook = new XSSFWorkbook(is);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.