我无法使用POI框架(HSSF)读取xlsm文件。我在读取xlsm文件时收到以下错误。
提供的数据似乎位于Office 2007+ XML中。您正在调用处理OLE2 Office文档的POI部分。您需要调用POI的不同部分来处理此数据(例如,XSSF而不是HSSF)
我也试过通过XSSF读取文件。即使这样也无法解决问题。任何人都可以告诉我如何使用poi框架在java代码中读取xlsm文件并将新工作表写入该文件。
答案 0 :(得分:4)
首先下载这些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();
}
}
}
答案 1 :(得分:1)
好像你正在使用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);