我编写了一个使用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>
谢谢!
答案 0 :(得分:0)
这不作为评论工作,所以我在没有测试的情况下发布答案(因为我无法测试):
// 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.