使用Java中的POI Framework读取xlsm文件时出错 [英] Error while reading an xlsm file using POI Framework in Java
问题描述
我无法使用POI Framework(HSSF)读取xlsm文件。我在读取xlsm文件时收到以下错误。
I am not able to read an xlsm file using the POI Framework (HSSF). I am getting the following error while reading an xlsm file.
提供的数据似乎在Office 2007+ XML中。您正在调用处理OLE2 Office文档的POI部分。你需要调用POI的不同部分来处理这些数据(例如XSSF而不是HSSF)
The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
我也试过通过XSSF读取文件。即使这样也无法解决问题。任何人都可以告诉我如何使用poi框架在java代码中读取xlsm文件并将新工作表写入该文件。
I tried reading the file through XSSF also. Even that doesn't solve the problem. Can anyone tell me how to read a xlsm file in java code using the poi framework and write a new sheet to that file.
推荐答案
首先下载这些JAR并在构建路径中添加它们:
First download these JARs and add them in build path:
- xmlbeans-2.3.0.jar
- poi-ooxml-schemas-3.7.jar
- poi-ooxml-3.9.jar
- poi-3.9.jar
- dom4j-1.6.1.jar
- xmlbeans-2.3.0.jar
- poi-ooxml-schemas-3.7.jar
- poi-ooxml-3.9.jar
- poi-3.9.jar
- dom4j-1.6.1.jar
现在您可以尝试使用此代码。它将读取XLSX和XLSM文件:
Now you can try this code. It will read XLSX and XLSM files:
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();
}
}
}
这篇关于使用Java中的POI Framework读取xlsm文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!