我无法使用 POI 框架 (HSSF) 读取 xlsm 文件。读取 xlsm 文件时出现以下错误。
提供的数据似乎在 Office 2007+ XML 中。您正在调用处理 OLE2 Office 文档的 POI 部分。您需要调用 POI 的不同部分来处理此数据(例如 XSSF 而不是 HSSF)
我也尝试通过 XSSF 读取文件。即使这样也不能解决问题。谁能告诉我如何使用 poi 框架读取 java 代码中的 xlsm 文件并将新工作表写入该文件。
首先下载这些 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();
}
}
}
看来您正在使用 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
然后你可以使用 Row 和 Cell 类来读取内容
最后写做这个
FileOutputStream fileOut=new FileOutputStream("d:\\excelfiles\\WeeklyStatusReport.xlsm");
wb.write(fileOut);