我正在尝试创建一个仅包含“ hello”的新excel文件。
这是我的代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author kamal
*/
public class JavaApplication4 {
private static String dir = "";
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
JFileChooser jc = new JFileChooser();
jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int output = jc.showOpenDialog(null);
if(output == JFileChooser.APPROVE_OPTION){
File f = jc.getSelectedFile();
String directory = f.getAbsolutePath();
setDir(directory);
}
FileOutputStream out = new FileOutputStream(new File(getDir()+"\\Book2.xlsx"));
FileInputStream in = new FileInputStream(new File(getDir()+"\\Book2.xlsx"));
org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(in);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0).createCell(0).setCellValue("hello");
workbook.write(out);
workbook.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @return the dir
*/
public static String getDir() {
return dir;
}
/**
* @param dir the dir to set
*/
public static void setDir(String directory) {
dir = directory;
}
}
..当我运行它时,出现以下错误:
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at javaapplication4.JavaApplication4.main(JavaApplication4.java:46)
C:\Users\kamal\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 7 seconds)
我在youtube上查找了此代码,但相同,但是我不确定为什么会收到错误?你能帮我吗?
最佳答案
我认为最可能的解释是该文件已损坏,或者它是XSSFWorkbook无法理解的较旧格式的电子表格文件。
如果不查看文件本身,几乎没有人可以给您明确的诊断。
关于java - 如何在Java Apache POI中修复NotOfficeXmlFileException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43641081/