以下是我阅读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
赞赏是否有人可以提供建议/帮助。感谢。
答案 0 :(得分:36)
答案 1 :(得分:0)
在这篇文章的日期,EPPLUS(v4.4.1)似乎处理xls文件就像使用xlsx一样:
以下是一个例子:
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");
它没有任何问题。
答案 2 :(得分:0)
在使用EPPlus读取Excel工作表之前,您需要将XLS转换为XLSX格式。您可以在this帖子中找到更多信息。
答案 3 :(得分:0)
解决方案,如果您想使用Epplus并且您的Eplus版本不支持.xlx
注意:如果您可以将.xlx文件转换为.xlsx,则可以跳过以下步骤
您可以更改文件类型。(办公室10或更高版本)
1> File
2> Save & Send
3> File Types > Change File Type
4> Workbook File Types > Select Workbook
5> Click Save As
完成上述步骤后,您的文件将另存为.xlsx格式