尝试在mac osx环境中使用Apache POI 3.8读取文件,该环境是在Windows中使用Open XML SDK 2.0 for Microsoft Office创建的,因为无法加载xlsx文件而导致空指针异常。下面是堆栈跟踪。我可以打开文件并查看它。
相同的代码适用于我在mac os env中创建的文件。如果我在处理之前打开并保存文件,则没有任何问题。注意:保存后文件大小会增加。是在.net中生成文件并在mac osx环境中处理的问题。
任何线索我为什么会遇到错误。
Caused by: java.lang.NullPointerException
at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead(XSSFWorkbook.java:253)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:159)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:183)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:73)
该类如下所示,使用实用方法,没有复制整个类。但这在创建工作簿时在行wb = new XSSFWorkbook(bis)
处发生。我尝试了WorkbookFactory.create(bis)
而不是XSSFWorkbook
等几个选项,但错误仍然相同,问题主要在于文件内容。
public class XLSXReader {
private BufferedInputStream bis;
private boolean hasNext = true;
int skipLines;
private boolean linesSkiped;
// The default line to start reading.
public static final int DEFAULT_SKIP_LINES = 0;
private XSSFWorkbook wb =null;
private XSSFSheet sheet=null;
private int noOfCols;
public XLSXReader(InputStream is){
bis = new BufferedInputStream(is);
this.noOfCols=0;
try {
wb = new XSSFWorkbook(bis);
sheet = wb.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
}
}
// with basic utility methods ....
}
答案 0 :(得分:0)
我认为,您错过了class path
问题。请尝试以下方式。
确保properties
directry必须位于class path
。
将您的doucments文件放在这些文件夹中。
public class WorkBookReader {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("properties/workbook.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(5);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Hello!");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("properties/workbook.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
}
}