我无法使用POI框架(HSSF)读取xlsm文件。阅读xlsm文件时出现以下错误。在Java中使用POI框架读取xlsm文件时出错
提供的数据似乎在Office 2007+ XML中。您正在调用处理OLE2 Office文档的POI部分。你需要调用POI的不同部分来处理这些数据(例如XSSF而不是HSSF)
我试着通过XSSF来读取文件。即使这样也不能解决问题。任何人都可以告诉我如何使用poi框架在Java代码中读取xlsm文件,并向该文件写入新的工作表。
我无法使用POI框架(HSSF)读取xlsm文件。阅读xlsm文件时出现以下错误。在Java中使用POI框架读取xlsm文件时出错
提供的数据似乎在Office 2007+ XML中。您正在调用处理OLE2 Office文档的POI部分。你需要调用POI的不同部分来处理这些数据(例如XSSF而不是HSSF)
我试着通过XSSF来读取文件。即使这样也不能解决问题。任何人都可以告诉我如何使用poi框架在Java代码中读取xlsm文件,并向该文件写入新的工作表。
看来你正在使用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);
第一下载这些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();
}
}
}
这对于.xlsm文件不起作用,并且出现Outofmemory异常 –
工程很好。你必须有一个不同的问题。 –