繁体   English   中英

使用Epplus创建没有绝对(文件)路径的Excel文件

[英]Creating Excel file without an Absolute (file) Path with Epplus

我编写了一个使用Epplus创建非常简单的Excel文件的应用程序(五列,唯一的特殊格式是粗体标题栏)。 然后,该文件由其他人移动,将其导入到单独的系统中,但是文件导入失败。 我跟踪了失败的原因,这是因为Excel文件在workbook.xml中指定了绝对路径。 Excel的文件验证器会警告该问题,告诉Excel从文件标记中删除绝对路径即可解决此问题。

有谁知道如何确保Epplus不会将文件的绝对路径添加到文件中? 这是我的代码:

using (var pkg = new ExcelPackage(new FileInfo(path))) // "path" is an absolute path to a directory on a shared drive
{
     var sheet = pkg.Workbook.Worksheets.Add("Manifest");
     var w = new ExcelWriter<ManifestLine>(sheet);

     // ... Write data ...

     await w.CloseAsync(Token).ConfigureAwait(false);
     pkg.Save();
}

这是工作簿的标记:(需要删除absPath)

<x:workbook xmlns:x15ac="http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main" mc:Ignorable="x15" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
      <x:fileVersion appName="xl" lastEdited="6" lowestEdited="6" rupBuild="14420" />
      <x:workbookPr defaultThemeVersion="153222" />
      <mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
        <mc:Choice Requires="x15">
          <x15ac:absPath xmlns:x15ac="http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac" url="Y:\ABC\Manifests\" />
        </mc:Choice>
      </mc:AlternateContent>
      <x:bookViews>
        <x:workbookView xWindow="0" yWindow="0" windowWidth="19065" windowHeight="9660" />
      </x:bookViews>
      <x:sheets>
        <x:sheet name="Manifest" sheetId="1" r:id="rId1" />
      </x:sheets>
      <x:calcPr calcId="0" />
    </x:workbook>

谢谢!

这不能很好地用作评论,因此我发布的答案没有经过测试(因为我无法测试):

// Save current dir before changing directories
var currentDir = Directory.GetCurrentDirectory();

// Change to directory where the file is
Directory.ChangeDirectory(Path.GetDirectoryName(path));

// Pass in *only* the filename, not the whole path
// Because we changed to that file's directory the rest of the code should find it without needing the whole path
using (var pkg = new ExcelPackage(new FileInfo(Path.GetFilename(path))))
{
     var sheet = pkg.Workbook.Worksheets.Add("Manifest");
     var w = new ExcelWriter<ManifestLine>(sheet);

     // ... Write data ...

     await w.CloseAsync(Token).ConfigureAwait(false);
     pkg.Save();
}

Directory.ChangeDirectory(currentDir);  // Change back to whatever directory the program was in before all this.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM