我無法使用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異常 –
工程很好。你必須有一個不同的問題。 –