java - 使用默认程序打开 Excel 文件

标签 java excel jexcelapi

我的程序成功创建并填充了一个 Excel(.xls) 文件。创建后,我希望新文件在系统的默认程序中打开(在我的例子中是 Excel)。我怎样才能做到这一点?

对于我想在记事本中打开 txt 文件的旧程序,我使用了以下内容:

if (!Desktop.isDesktopSupported()) {
        System.err.println("Desktop not supported");
        // use alternative (Runtime.exec)
        return;
    }

    Desktop desktop = Desktop.getDesktop();
    if (!desktop.isSupported(Desktop.Action.EDIT)) {
        System.err.println("EDIT not supported");
        // use alternative (Runtime.exec)
        return;
    }

    try {
        desktop.edit(new File(this.outputFilePath));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

当我尝试将此代码用于 Excel 文件时,出现以下错误:

java.io.IOException: Failed to edit file:C:/foo.xls

建议?

最佳答案

尝试使用 Desktop.open() 而不是 Desktop.edit() :

Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));

如果 Desktop.open() 不可用,则可以使用 Windows 文件关联:

Process p = 
  Runtime.getRuntime()
   .exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);

关于java - 使用默认程序打开 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114318/

相关文章:

java - 燃料图平滑算法

java - 从自定义 Web 服务器迁移到 apache Web 服务器

java - 如何在 JavaFX Canvas 中同步多个图像的旋转

excel - 将范围设置为值而不重新格式化单元格

vba - 有条件地检查 VBA 中的 XPath 是否正确

java - 使用 JExcel API,如何在不添加隐藏撇号的情况下输入未知数据类型的单元格值?

java - 错误 "; expected",sql 语句

excel - cfspreadsheet 能否在不将它们更改为空白的情况下从查询中输出空值?

java - 如果第一个工作表已满,如何在 Excel 中添加其他工作表

java - 如何使用jexcel读取excel?