而阅读在Java中使用POI框架的XLSM文件时出错(Error while reading an

2019-08-01 10:03发布

我无法读取使用POI框架(HSSF)的XLSM文件。 在读取XLSM文件我收到以下错误。

所提供的数据似乎是在Office 2007+ XML。 您正在呼吁与OLE2 Office文档涉及POI的一部分。 你需要调用POI的不同部分来处理此数据(例如XSSF而不是HSSF)

我试图读取该文件通过XSSF也。 即使是不解决问题。 谁能告诉我如何读取使用POI框架在Java代码中XLSM文件,并写入新的表到该文件。

Answer 1:

首先下载这些JAR和构建路径添加它们:

  • XMLBeans的-2.3.0.jar
  • POI-OOXML-模式-3.7.jar
  • POI-OOXML-3.9.jar
  • POI-3.9.jar
  • dom4j的-1.6.1.jar

现在,你可以试试这个代码。 它会读取XLSX和XLSM文件:

import java.io.File;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ReadMacroExcel {
public static void main(String[] args) {
 try {
     //Create a file  from the xlsx/xls file
          File f=new File("F:\\project realated file\\micro.xlsm");

          //Create Workbook instance holding reference to .xlsx file
          org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(f);
          System.out.println(workbook);

     //printing number of sheet avilable in workbook
     int numberOfSheets = workbook.getNumberOfSheets();
     System.out.println(numberOfSheets);
     org.apache.poi.ss.usermodel.Sheet sheet=null; 
   //Get the  sheet in the xlsx file
     for (int i = 0; i < numberOfSheets; i++) {


      sheet = workbook.getSheetAt(i);
     System.out.println(sheet.getSheetName());

   //Iterate through each rows one by one
     Iterator<Row> rowIterator = sheet.iterator();
     while (rowIterator.hasNext())
     {
         Row row = rowIterator.next();
         //For each row, iterate through all the columns
         Iterator<Cell> cellIterator = row.cellIterator();

         while (cellIterator.hasNext())
         {
             Cell cell = cellIterator.next();
             //Check the cell type and format accordingly
             switch (cell.getCellType())
             {
                 case Cell.CELL_TYPE_NUMERIC:
                     System.out.print(cell.getNumericCellValue() + "t");
                     break;
                 case Cell.CELL_TYPE_STRING:
                     System.out.print(cell.getStringCellValue() + "t");
                     break;
             }
         }
         System.out.println("");
     }
 }
 }
 catch (Exception e)
 {
     e.printStackTrace();
 }


    }
}


Answer 2:

看来你正在使用Apache的POI。

我用下面的代码来阅读我的XLSM文件

FileInputStream fileIn=new FileInputStream("d:\\excelfiles\\WeeklyStatusReport.xlsm");

Workbook wb=WorkbookFactory.create(fileIn);      //this reads the file

final Sheet sheet=wb.getSheet("Sheet_name");  //this gets the existing sheet in xlsmfile
//use wb.createSheet("sheet_name"); to create a new sheet and write into it

然后你可以使用行和单元格类阅读内容

最后写做

FileOutputStream fileOut=new FileOutputStream("d:\\excelfiles\\WeeklyStatusReport.xlsm");
wb.write(fileOut);


文章来源: Error while reading an xlsm file using POI Framework in Java
标签: java excel xlsm