GVKun编程网logo

使用Apache POI读取xlsx文件时出现异常(org.apache.poi.openxml4j.exception-无内容类型[M1.13])?

5

在本文中,我们将带你了解使用ApachePOI读取xlsx文件时出现异常在这篇文章中,我们将为您详细介绍使用ApachePOI读取xlsx文件时出现异常的方方面面,并解答org.apache.poi.

在本文中,我们将带你了解使用Apache POI读取xlsx文件时出现异常在这篇文章中,我们将为您详细介绍使用Apache POI读取xlsx文件时出现异常的方方面面,并解答org.apache.poi.openxml4j.exception-无内容类型[M1.13]?常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的Apache POI创建损坏的XLSX文件、Apache POI读取Excel、Exception java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocumentPart、java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表

本文目录一览:

使用Apache POI读取xlsx文件时出现异常(org.apache.poi.openxml4j.exception-无内容类型[M1.13])?

使用Apache POI读取xlsx文件时出现异常(org.apache.poi.openxml4j.exception-无内容类型[M1.13])?

我正在使用Apache POI(XSSF API)来读取xlsx文件。当我尝试读取file.i时出现以下错误:

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

码:

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 loadxlsFilepublic 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; }

请帮助我解决此问题。

谢谢

答案1

小编典典

该错误告诉您POI找不到OOXML文件的核心部分,在这种情况下为内容类型部分。您的文件不是有效的OOXML文件,更不用说有效的.xlsx文件了。不过,这是一个有效的zip文件,否则您将遇到较早的错误

Excel可以真正加载该文件吗?我希望它不能,因为异常通常是通过给POI一个常规的.zip文件触发的!我怀疑您的文件无效,因此例外

更新: 在Apache POI 3.15(从beta
1开始)中,对于此问题的更常见原因,有一组更有用的Exception消息。在这种情况下,您现在将获得更多描述性异常,例如ODFNotOfficeXmlFileException和OLE2NotOfficeXmlFileException。仅当POI确实不知道您提供的内容是什么,但知道它已损坏或无效时,才应显示此原始表单。

Apache POI创建损坏的XLSX文件

Apache POI创建损坏的XLSX文件

使用

org.apache.poi.ss.usermodel.WorkbookFactory

//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true);  //true creates XSSF formatted file

将向您返回的一个实例

org.apache.poi.ss.usermodel.Workbook

然后您可以使用来写文件

Workbook.write(OutputStream)

解决方案:

try (Workbook wb = WorkbookFactory.create(true)) {
    Sheet sheet = wb.createSheet("new sheet");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Hellooooo");
    try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
        wb.write(fos);
    }
}

Apache POI读取Excel

Apache POI读取Excel

 1、pom.xml配置文件

 1 <!-- 配置Apache POI -->
 2         <dependency>
 3             <groupId>org.apache.poi</groupId>
 4             <artifactId>poi</artifactId>
 5             <version>4.1.0</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.apache.poi</groupId>
 9             <artifactId>poi-ooxml</artifactId>
10             <version>4.1.0</version>
11         </dependency>
12         <dependency>
13             <groupId>org.apache.poi</groupId>
14             <artifactId>poi-ooxml-schemas</artifactId>
15             <version>4.1.0</version>
16         </dependency>

2、读取Excel的Java代码

 1 @Test
 2     public void readExcelTest() throws IOException {
 3         File xlsFile = new File("E:\\book.xlsx");
 4         // 获得工作簿
 5         XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(xlsFile));
 6         // 获得sheet
 7         XSSFSheet sheet = wb.getSheetAt(0);
 8         int rows = sheet.getPhysicalNumberOfRows();
 9         String split = "**********";
10         for (int i = 0; i < rows; i++) {
11             // 获取第i行
12             XSSFRow row = sheet.getRow(i);
13             // 列数
14             short nums = row.getLastCellNum();
15             for (int j = 0; j < nums; j++) {
16                 Cell cell = row.getCell(j);
17                 System.out.print(cell + split);
18             }
19             System.out.println();
20         }
21     }

3、Excel文件和测试结果

 

以上只是java读取Excel应用演示,代码中没有对对象的非空判定,需要的童鞋可自行加上判定,使代码更健壮。

Exception java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocumentPart

Exception java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocumentPart

不会替换 jar 包可以参考这篇文章 不重新打包,只修改 jar 包中的某个文件、某个类

1. 功能:Word 转 PDF

2. 使用包的版本如下

POI    PDF
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

<dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.xdocreport.itext.extension</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
            <version>1.0.6</version>
        </dependency>

3. 问题:

关键出错 jar 包:org.apache.poi.xwpf.converter.core 

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocumentPart
    at org.apache.poi.xwpf.converter.core.styles.XWPFStylesdocument.getFontsdocument(XWPFStylesdocument.java:1477)
    at org.apache.poi.xwpf.converter.core.styles.XWPFStylesdocument.<init>(XWPFStylesdocument.java:190)
    at org.apache.poi.xwpf.converter.core.styles.XWPFStylesdocument.<init>(XWPFStylesdocument.java:184)
    at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.createStylesdocument(XWPFDocumentVisitor.java:166)
    at org.apache.poi.xwpf.converter.core.XWPFDocumentVisitor.<init>(XWPFDocumentVisitor.java:159)
    at org.apache.poi.xwpf.converter.pdf.internal.PdfMapper.<init>(PdfMapper.java:149)
    at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:55)
    at org.apache.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:38)
    at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
    at com.test.WordPdfUtils.wordConverterToPdf(WordPdfUtils.java:113)
    at com.test.WordPdfUtils.wordConverterToPdf(WordPdfUtils.java:66)
    at com.test.WordPdfUtils.main(WordPdfUtils.java:47)
Caused by: java.lang.classNotFoundException: org.apache.poi.POIXMLDocumentPart
    at java.net.urlclassloader.findClass(urlclassloader.java:381)
    at java.lang.classLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.classLoader.loadClass(ClassLoader.java:357)
    ... 12 more

3. 原因:POI高版本的包中 org.apache.poi.POIXMLDocumentPart 类的改动很大,而相应的 pdf 包已经很久没有维护目前是1.0.6(如果使用POI3.0的版本还是可以的)

4. 解决方案

(2-1) 下载源码,org.apache.poi.xwpf.converter.core 源码包下载链接

(2-2) 修改  org.apache.poi.xwpf.converter.core.styles.XWPFStylesdocument 类中调用 POIXMLDocumentPart 的部分

一共四行代码,第一行是引包,其他三行是一样的,详细见下图

5. 打包方法参考

(1)修改后自己正常打包就可以,手动替换一下本地 maven 目录下的 org.apache.poi.xwpf.converter.core 包

(2)或者可以在自己的项目中,单独创建这个目录和修改后的类

6. 资源

修改后的类以及Word转PDF工具类

(修改后的 org.apache.poi.xwpf.converter.core.styles.XWPFStylesdocument

以及Word转PDF的工具类)
 

java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表

java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表

我正在尝试使用Apache Poi将ResultSet写入Excel(* .xlsx)表.

Office Excel中的表对象错误无效

但是,即使它写入Excel文件没有任何错误,当我尝试在Office Excel 2013中打开它时,它会显示错误并删除表对象以仅提供纯数据视图.

这是粗略的示例代码using this example:

public static void writeExcel(ResultSet rs,int sqliteRowCount,String dir) {
    System.out.println("Writing Excel(*.xlsx) File...");
    XSSFWorkbook workbook = null;
    try {
        if (rs != null) {
            // Get ResultSet MetaData
            ResultSetMetaData rsmd = rs.getMetaData();
            // Number of columns
            int numColumns = rsmd.getColumnCount();
            // Number of rows
            // + 1 for headers
            int numRows = sqliteRowCount + 1;
            workbook = new XSSFWorkbook();

            // Create Excel Table
            XSSFSheet sheet = workbook.createSheet("Text");
            XSSFTable table = sheet.createTable();
            table.setdisplayName("Test");
            CTTable cttable;
            cttable = table.getCTTable();

            // Style configurations
            CTTableStyleInfo style = cttable.addNewTableStyleInfo();
            style.setName("TableStyleMedium16");
            style.setShowColumnStripes(false);
            style.setShowRowStripes(true);

            // Set Table Span Area
            AreaReference reference = new AreaReference(new CellReference(0,0),new CellReference(numRows - 1,numColumns - 1));
            cttable.setRef(reference.formatAsstring());
            cttable.setId(1);
            cttable.setName("Test");
            cttable.setdisplayName("Test");
            cttable.setTotalsRowCount(numRows);
            cttable.setTotalsRowShown(false);

            // Create Columns
            CTTableColumns columns = cttable.addNewTableColumns();
            columns.setCount(numColumns);

            // Create Column,Row,Cell Objects
            CTTableColumn column;
            XSSFRow row;

            // Add Header and Columns
            XSSFRow headerRow = sheet.createRow(0);
            for (int i = 0; i < numColumns; i++) {
                column = columns.addNewTableColumn();
                column.setName("Column" + (i + 1));
                column.setId(i + 1);
                headerRow.createCell(i).setCellValue(rsmd.getColumnLabel(i + 1));
            }

            // Write each row from ResultSet
            int rowNumber = 1;
            while (rs.next()) {
                row = sheet.createRow(rowNumber);
                for (int y = 0; y < numColumns; y++) {
                    row.createCell(y).setCellValue(rs.getString(y + 1));
                }
                rowNumber++;
            }

            // Set AutoFilter
            CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
            fltr.setRef((new AreaReference(new CellReference(0,numColumns - 1))).formatAsstring());
            cttable.setAutoFilter(fltr);
            // sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0,numColumns - 1))).formatAsstring()));
            // Freeze Pan
            sheet.createFreezePane(0,1,2);
        }
    } catch (sqlException ex) {
        System.out.println("sql Error while writing Excel file!");
    } finally {
        try {
        // Let's write the excel file Now
            if (workbook != null) {
                String excelDir = dir + File.separator + "workbook.xlsx";
                try (final FileOutputStream out = new FileOutputStream(excelDir)) {
                    workbook.write(out);
                }
            }
        } catch (IOException ex) {
            System.out.println("IO Error while writing Excel summary file!");
        }
    }
}

我知道我的代码有问题,但无法弄明白.
任何想法,为什么会发生这种情况,我的代码中可能存在错误.

更新1:

如果使用Apache POI创建,则在Excel存档中使用表格XML文件

<?xml version="1.0" encoding="UTF-8"?>
<table displayName="Test" ref="A1:B881" id="1" name="Test" totalsRowCount="881" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn name="ID" id="1"/><tableColumn name="Name" id="2"/><tableStyleInfo name="TableStyleMedium2" showColumnStripes="true" showRowStripes="true"/></table>

如果手动创建表,则在Excel归档中使用表格XML文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table1" displayName="Table1" ref="A1:B881" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn id="1" name="ID"/><tableColumn id="2" name="Name"/></tableColumns><tableStyleInfo name="TableStyleLight9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/></table>

此外,如果我打开Excel存档,它在Apache POI创建的主题文件夹中没有主题文件夹,但它存在于Office Excel中手动创建的主题文件夹中.奇怪.

更新2:
示例可执行代码(使用Netbeans):

/*
 * To change this license header,choose License Headers in Project Properties.
 * To change this template file,choose Tools | Templates
 * and open the template in the editor.
 */

package apachepoi_exceltest;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.poi.ss.util.AreaReference;
    import org.apache.poi.ss.util.CellRangeAddress;
    import org.apache.poi.ss.util.CellReference;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFTable;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;

    /**
     *
     */
    public class ApachePOI_ExcelTest {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {

            String outputDir = "Your Local Directory Here";

            // Todo code application logic here
            HashMap<String,String> dataMap = new HashMap<>();

            dataMap.put("ID 1","Dummy Name 1");
            dataMap.put("ID 2","Dummy Name 2");
            dataMap.put("ID 3","Dummy Name 3");
            dataMap.put("ID 4","Dummy Name 4");

            writeExcel(dataMap,outputDir);

        }

        private static void writeExcel(HashMap<String,String> dataMap,String outputDir) {
            System.out.println("Writing Excel(*.xlsx) Summary File...");
            XSSFWorkbook workbook = null;
            try {

                // Number of columns
                int numColumns = 2; // ID and Name
                // Number of rows
                int numRows = dataMap.size() + 1; // +1 for header

                // Create Workbook
                workbook = new XSSFWorkbook();

                // Create Excel Table
                XSSFSheet sheet = workbook.createSheet("Summary");
                XSSFTable table = sheet.createTable();
                table.setdisplayName("Test");
                CTTable cttable;
                cttable = table.getCTTable();

                // Style configurations
                CTTableStyleInfo style = cttable.addNewTableStyleInfo();
                style.setName("TableStyleMedium16");
                style.setShowColumnStripes(false);
                style.setShowRowStripes(true);

                // Set Tabel Span Area
                AreaReference reference = new AreaReference(new CellReference(0,numColumns - 1));
                cttable.setRef(reference.formatAsstring());
                cttable.setId(1);
                cttable.setName("Test");
                cttable.setdisplayName("Test");
                cttable.setTotalsRowCount(numRows);
                cttable.setTotalsRowShown(false);

                // Create Columns
                CTTableColumns columns = cttable.addNewTableColumns();
                columns.setCount(numColumns);

                // Create Column,Cell Objects
                CTTableColumn column;
                XSSFRow row;

                // Add ID Header
                column = columns.addNewTableColumn();
                column.setName("Column" + (1));
                column.setId(1);

                // Add Name Header
                column = columns.addNewTableColumn();
                column.setName("Column" + (1));
                column.setId(1);

                // Add Header Row
                XSSFRow headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("ID");
                headerRow.createCell(1).setCellValue("Name");

                int rowNumber = 1;
                for (Map.Entry<String,String> entry : dataMap.entrySet()) {
                    String id = entry.getKey();
                    String name = entry.getValue();
                    row = sheet.createRow(rowNumber);
                    row.createCell(0).setCellValue(id);
                    row.createCell(1).setCellValue(name);
                    rowNumber++;
                }

                // Set Filter (Below three lines code somehow not working in this example,so setting AutoFilter to WorkSheet)
    //             CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
    //             fltr.setRef((new AreaReference(new CellReference(0,numColumns - 1))).formatAsstring());
    //             cttable.setAutoFilter(fltr);
                sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0,numColumns - 1))).formatAsstring()));

                // Freeze First Row as header Row
                sheet.createFreezePane(0,2);

            } catch (Exception ex) {
                System.out.println("Error while writing Excel summary file!");
            } finally {
                try {
                    // Lets write the Excel File Now
                    if (workbook != null) {
                        String excelDir = outputDir + File.separator + "workbook.xlsx";
                        try (final FileOutputStream out = new FileOutputStream(excelDir)) {
                            workbook.write(out);
                        }
                    }
                } catch (IOException ex) {
                    System.out.println("IO Error while writing Excel summary file!");
                }
            }
        }

    }

使用的库:

OOXML-模式-1.1.jar

POI-3.11-beta2-20140822.jar

POI-OOXML-3.11-beta2-20140822.jar

XMLBeans的-2.6.0.jar

解决方法

你的代码出了什么问题就是存在一行. “cttable.setTotalsRowCount(numRows行);” 删除它,一切都会工作. 如果有疑问,请比较在Excel中手动创建的某些工作表的XML定义以及使用Apache POI创建的定义

我们今天的关于使用Apache POI读取xlsx文件时出现异常org.apache.poi.openxml4j.exception-无内容类型[M1.13]?的分享就到这里,谢谢您的阅读,如果想了解更多关于Apache POI创建损坏的XLSX文件、Apache POI读取Excel、Exception java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocumentPart、java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表的相关信息,可以在本站进行搜索。

本文标签: