Java “包应包含内容类型部分 [M1.13]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32878743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:58:23  来源:igfitidea点击:

"Package should contain a content type part [M1.13]"

javaexcelapacheswingapache-poi

提问by Tephrite

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

我正在尝试写入 Excel 文件,但是我不断收到错误消息:

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

线程“main” org.apache.poi.POIXMLException 中的异常:org.apache.poi.openxml4j.exceptions.InvalidFormatException:包应包含内容类型部分 [M1.13]

From what I understand I am missing a jar file.

据我了解,我缺少一个 jar 文件。

Can anyone help me identify which file it is?

谁能帮我确定它是哪个文件?

P.S. I am using Netbeans.

PS我正在使用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);

    }      

}

回答by TAYFUN ?EL?K

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

检查 EXCEL 格式 .... 首先,我用 poi 创建了一个示例 excel,我第一次尝试更改了列,它给出了同样的错误,但几次尝试后它成功读取。我想知道为什么它第一次运行时不起作用:(但是如果您有正确的库,请检查正确的 excel 格式

回答by Gabriel Ullmann

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.

当您通过 LibreOffice 创建 XLS/XLSX 文件时,可能会发生这种情况。显然,转换过程中丢失了一些东西,并且该文件与 Microsoft Office 中制作的电子表格不同。我遇到了同样的错误,我的解决方案是将我在 LibreOffice Calc 中所做的所有工作复制到 MS Excel 电子表格,然后保存一个新文件。

回答by Hitesh Sahu

Use file extension to handle WorkSheetType

使用文件扩展名处理WorkSheet类型

  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

对于 XLSX 文件:使用 XSSFWorkbook & XSSFSheet

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

    XSSFSheet sheet = workbook.getSheetAt(0);

For XLS file: use HSSFWorkbook & HSSFSheet

对于 XLS 文件:使用 HSSFWorkbook & HSSFSheet

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

    HSSFSheet sheet = workbook.getSheetAt(0);

回答by Pham Hung

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.

我遇到了同样的问题。你的excel格式不正确。您可以将所有工作复制到新工作表或清除格式。祝你好运。

回答by Long Nguyen

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

我也有同样的问题。当您打开 excel 文件时,它会生成一些文件,例如~$______.xlsx只需找到并删除所有对我有用的文件即可。

回答by mike oganyan

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.

您所拥有的是 Excel 文件和您尝试创建的工作簿之间的版本不匹配。避免的最好方法是:选择接口实现。

I built on top of Hitesh Sahu's solution:

我建立在 Hitesh Sahu 的解决方案之上:

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");
}

回答by Micha? Soko?owski

Another possible solution is

另一种可能的解决方案是

Workbook workbook = WorkbookFactory.create(source)

WorkbookFactoryshould be provided by Apache POI you are using (if not upgrade to newer version). It recognize file format and creates concrete implementation of Workbookinterface (XSSFWorkbookor HSSFWorkbook). The sourceparameter can be java.io.InputStreamor java.io.File.

WorkbookFactory应该由您正在使用的 Apache POI 提供(如果没有升级到更新版本)。它识别文件格式并创建Workbook接口(XSSFWorkbookHSSFWorkbook)的具体实现。该source参数可以是java.io.InputStreamjava.io.File

回答by ChiNtu

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.

由于网络问题或格式损坏,您的应用程序尝试访问的 excel 文件没有响应会导致此错误。如果是由于网络问题尝试稍后运行应用程序(或)如果文件已损坏,请尝试放置新文件并测试您的应用程序。祝你好运。

回答by UzumakiL

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

好的,就我而言,这就是我的情况,而第 3 行抛出了这个异常:

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.

但是我发现 line3 不起作用,因为我还通过 line2 在我的 xlsx 文件上打开了一个输出流,然后执行 line3 失败了。我删除了 line2 以使其工作。

回答by Manpreet

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

我的excel表被加密了。删除了密码,它起作用了。