12

I am attempting to write to an Excel file however I keep getting the error:

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

From what I understand I am missing a jar file.

Can anyone help me identify which file it is?

P.S. I am using Netbeans.

my current files

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nicholaskissaun
 */

public class Tester {

    public static void main (String args \[\])throws FileNotFoundException, IOException, InvalidFormatException{     
        int RowCount = 7, iChoice;
        String sChoice;
        XSSFSheet s;
        XSSFRow row1;
        XSSFWorkbook wb;
        XSSFCell r1c1, r1c2, r1c8, r1Episodes;

        FileInputStream fis = new FileInputStream("/Users/nicholaskissaun/Google Drive/Grade 11_12/Computer Science/Java/Term1/src/IA/Profiles/Becky/ShowDetails.xlsx");           
        wb = new XSSFWorkbook(fis);  
        s = wb.getSheetAt(0);

    }      

}
Tephrite
  • 135
  • 1
  • 1
  • 5
  • 1
    The error is not about missing jar file. It is about missing content type part within the ShowDetails.xlsx file. So I suspect the ShowDetails.xlsx is not generated by Excel but by some third party software which does something wrong. Open the ShowDetails.xlsx with Excel, save it again with Excel and then try again with POI. – Axel Richter Oct 01 '15 at 05:56
  • @AxelRichter You were right, I re saved it and it worked however I got another error now haha. Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: org.apache.poi.util.POILogger.log(I[Ljava/lang/Object;)V – Tephrite Oct 01 '15 at 06:57
  • 1
    There is a mix of different POI versions in the ClassPath. See: http://poi.apache.org/faq.html#faq-N10006. But I've no experience with Netbeans. So I don't know how to clean up the ClassPath there. Maybe others know. – Axel Richter Oct 01 '15 at 07:27
  • @AxelRichter Thanks for your help! – Tephrite Oct 01 '15 at 10:43

12 Answers12

16

Use file extension to handle WorkSheet Type

  String inputFilename = new File(path).getName();

                    switch (inputFilename.substring(inputFilename.lastIndexOf(".") + 1,
                            inputFilename.length())) {
                        case "xls":
                            return readXLS(path);

                        case "xlsx":
                            return readXLSX(path);
                        default:
                            Log.e(TAG, "No XLS file chosen");
                            return "Please select valid \"Excel\" File\"";
                    }

For XLSX file: use XSSFWorkbook & XSSFSheet

    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

    XSSFSheet sheet = workbook.getSheetAt(0);

For XLS file: use HSSFWorkbook & HSSFSheet

    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(path)));

    HSSFSheet sheet = workbook.getSheetAt(0);
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
7

This may happen when your create your XLS/XLSX file through LibreOffice. Apparently something is lost in the conversion and the file is not the same as a spreadsheet made in Microsoft Office. I had the same error and the solution for me was copying all the work I have done in LibreOffice Calc to a MS Excel spreadsheet and then save a new file.

Gabriel Ullmann
  • 151
  • 4
  • 11
  • Thanks! It may also be because the hidden file starting with `~$` was selected instead of the normal one, if it is still open for editing in the application (my case). – Martin Patsov May 19 '20 at 12:03
3

What you have is version mismatch between your Excel file and workbook you are trying to create. The best way to avoid is: choose Interface implementation.

I built on top of Hitesh Sahu's solution:

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

Workbook workbook = null;

// parse files from request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartDataPointsFile = multipartRequest.getFile("yourFileHere");

try {
    if(multipartDataPointsFile!=null) {
        String originalFileName= multipartDataPointsFile.getOriginalFilename();
        if(originalFileName!=null && originalFileName.length()>0) {
            switch (originalFileName.substring(originalFileName.lastIndexOf(".") + 1,
                    originalFileName.length())) {
                case "xls":
                    try {
                        workbook = WorkbookFactory.create(multipartDataPointsFile.getInputStream());
                    }catch(org.apache.poi.openxml4j.exceptions.InvalidFormatException ie){
                        logger.error("Malformed Excel");
                        throw new IOException();
                    }
                    if(workbook!=null) {
                        // Do something in here
                    }else{
                        logger.error("Could not pass along the workbook");
                        throw new IOException();
                    }
                case "xlsx":
                    try {
                        workbook = WorkbookFactory.create(multipartDataPointsFile.getInputStream());
                    }catch(org.apache.poi.openxml4j.exceptions.InvalidFormatException ie){
                        logger.error("Malformed Excel");
                        throw new IOException();
                    }
                    if(workbook!=null) {
                          // Do something in here
                    }else{
                        logger.error("Could not pass along the workbook");
                        throw new IOException();
                    }
                default:
                    logger.error("File type is not  recognized  Excell type");
                    throw new IOException();
            }

        }else{
            logger.error("Can Not Read File Name");
            throw new IOException();  
        }
    }else{
        logger.error("Did not select a file");
        throw new IOException();
    }
} catch (IOException e) {
    throw new ApplicationErrorException("Can't parse  Excel file");
}
Pang
  • 9,564
  • 146
  • 81
  • 122
mike oganyan
  • 137
  • 5
1

I have the same problem. When you open excel file it will generate some file like ~$______.xlsx Just find and delete all of them worked for me.

Long Nguyen
  • 9,898
  • 5
  • 53
  • 52
  • These are temporary copies of the file to prevent it from being corrupted so you could restore them... But, this indeed solved my problem!!!! Just unbelievable!! – Shai Alon Dec 27 '20 at 20:18
0

CHECK EXCEL FORMAT .... Firstly I created an sample excel with poi and I changed the columns with mine first attempt it give same error but after few try it successfully read .I wonder why it didn't worked first run :( but If you have right library please check the correct excel format

0

I got the same problem. Your excel isn't in right format. You can copy all work to new sheet or do Clear Format. Good luck.

Pham Hung
  • 308
  • 1
  • 4
  • 14
0

Another possible solution is

Workbook workbook = WorkbookFactory.create(source)

WorkbookFactory should be provided by Apache POI you are using (if not upgrade to newer version). It recognize file format and creates concrete implementation of Workbook interface (XSSFWorkbook or HSSFWorkbook). The source parameter can be java.io.InputStream or java.io.File.

0

The excel file which your application trying to access is not responding due to network issues or corrupted format causes this error. If it is due to network issue try to run application later (or) If file is corrupted, try to put new file and test your application. Good Luck.

ChiNtu
  • 1
0

Ok in my case this is how I had it and line3 was throwing this exception:

File xlsxFile = new File( "C:\\myWorkbook.xlsx" );
FileInputStream finXLSX = new FileInputStream( xlsxFile ); //line1

FileOutputStream foutXLSX = new FileOutputStream( xlsxFile ); //line2

XSSFWorkbook workSheet = new XSSFWorkbook( finXLSX ); //line3

But I figured out that line3 wasn't working as I had also opened an output stream on my xlsx file via line2 and then doing line3 was failing. I removed line2 to make it work.

UzumakiL
  • 373
  • 3
  • 9
0

My excel sheet was encrypted. Deleted the password and it worked.

0

I came across similar issue, finally found that file was having sensitivity --> as confidential, change it to public ..solved my issue. all the best

0

The file could be opened in the background.... that just happened to me

Capps99
  • 111
  • 1
  • 3