代码之家  ›  专栏  ›  技术社区  ›  Maxter

在临时文件中打开Excel文件

  •  0
  • Maxter  · 技术社区  · 7 年前

    我使用excel interop已经有一段时间了,但是出于某些原因,我决定开始使用epplus库。 我喜欢它,但是我想像打开excel互操作一样打开excel文件:将文件作为一个临时文件打开,这个文件实际上不存在于任何地方。 到目前为止,epplus必须将文件保存在某个地方,以便我可以使用以下命令打开它:

    System.Diagnostics.Process.Start()
    

    到目前为止,我尝试的是在打开文件后将其删除:

    excelPack.SaveAs(new FileInfo(name));                                                          
    File.SetAttributes(name, FileAttributes.ReadOnly); //Force the user to save file As                                        
    System.Diagnostics.Process.Start(name);                                                                         
    File.Delete(name); //Crash here. File is in use
    

    但正如您所见,它在最后一行崩溃,因为文件已打开。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Maxter    7 年前

    解决办法很简单。只需在删除之前将文件属性设置为normal。这将以某种方式告诉windows该文件不再使用:

                    excelPack.SaveAs(new FileInfo(name));                                                          
                    File.SetAttributes(name, FileAttributes.ReadOnly); //Force the user to save file As                                        
                    System.Diagnostics.Process.Start(name);
                    File.SetAttributes(name, FileAttributes.Normal);                                                                     
                    File.Delete(name); 
    

    文件将被删除,但仍将以只读方式在Excel中打开。用户将能够保存它。