Epplus无法读取Excel文件。

29

以下是我读取 Excel 文件的代码。

代码。

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xls");
ExcelPackage pck = new ExcelPackage(newFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;
ws.Cells["J12"].Value = "Test Write";
pck.Save();
System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xls");
当我运行这段代码时,它会抛出一个运行时错误。
错误。
System.Exception: Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password ---> System.IO.FileFormatException: File contains corrupted data.
   at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream)
   at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.SeekableLoad(ZipIOBlockManager blockManager)
   at MS.Internal.IO.Zip.ZipArchive..ctor(Stream archiveStream, FileMode mode, FileAccess access, Boolean streaming, Boolean ownStream)
   at MS.Internal.IO.Zip.ZipArchive.OpenOnStream(Stream stream, FileMode mode, FileAccess access, Boolean streaming)
   at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming)
   at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
   at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess)
   at OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password)
   --- End of inner exception stack trace ---
   at OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password)
   at OfficeOpenXml.ExcelPackage..ctor(FileInfo newFile)
   at Report.Form1.ExportToExcel1(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 39

希望有人能够提供建议/帮助。谢谢。

3个回答

46

据我所知,Epplus无法处理 .xls(BIFF8格式)文件。

它能够处理新的 .xlsx(Open Office Xml)格式。

不过,您可以使用excellibrary 来处理 xls 文件。


1
不错的库。虽然不快,但不用担心 Com-foolery。 - Jack
很好的库,它支持 .xls 和 .xlsx 两种格式吗?另外一个问题是它是否类似于 ExpertXls.ExcelLibrary - Iswar
谢谢,伙计。我一直在努力弄清楚为什么EPPlus打不开Excel,结果原来是XLS格式。 - undefined

1
在本文发布日期时,EPPLUS(v4.4.1)似乎能够像处理xlsx文件一样处理xls文件:
以下是一个示例:
  using (var target = new ExcelPackage(new System.IO.FileInfo("D:\\target.xls")))
        {
            target.Workbook.Worksheets.Add("worksheet");
            target.Workbook.Worksheets.Last().Cells["A1:A12"].Value = "Hi";
            target.Save();
        }

也测试了你的代码:

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xls");
ExcelPackage pck = new ExcelPackage(newFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;
ws.Cells["J12"].Value = "Test Write";
pck.Save();
System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xls");

而且它可以正常运行,没有任何问题。

生成的文件仍然是OpenXML格式,只是扩展名不同。Excel在打开文件时会提示。此外,GitHub页面也没有提到任何xls支持。 - FrankM

0

在使用EPPlus读取Excel表之前,您需要将XLS格式转换为XLSX格式。您可以在this帖子中找到更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接