C# 如何访问 EPPlus 中的工作表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13568411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:01:43  来源:igfitidea点击:

How to access worksheets in EPPlus?

c#epplus

提问by Shane Courtrille

I'm using the 3.1 release of EPPlus library to try to access a worksheet in an Excel file. When I try either of the following methods I get a System.ArgumentException : An item with the same key has already been added.

我正在使用 EPPlus 库的 3.1 版本尝试访问 Excel 文件中的工作表。当我尝试以下任一方法时,我会得到一个System.ArgumentException : An item with the same key has already been added.

using (ExcelPackage package = new ExcelPackage(new FileInfo(sourceFilePath)))
{
   var worksheet = package.Workbook.Worksheets[0];

   // OR

   foreach (var excelWorksheet in package.Workbook.Worksheets)
   ...
}

Exception Stack:

异常堆栈:

System.ArgumentException : An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource?resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey?key,?TValue?value,?Boolean?add)
   at System.Collections.Generic.Dictionary`2.Add(TKey?key,?TValue?value)
   at OfficeOpenXml.ExcelNamedRangeCollection.Add(String?Name,?ExcelRangeBase?Range)
   at OfficeOpenXml.ExcelWorkbook.GetDefinedNames()
   at OfficeOpenXml.ExcelPackage.get_Workbook()

This seems like very basic functionality to have be so broken.. am I doing something wrong?

这似乎是非常基本的功能被破坏了..我做错了什么吗?

采纳答案by Shane Courtrille

The workbook in question had named ranges defined. These were causing problems so I created a new xlsx file with just the data I needed and it was able to open fine.

有问题的工作簿定义了命名范围。这些导致了问题,因此我创建了一个新的 xlsx 文件,其中仅包含我需要的数据,并且能够正常打开。

回答by Pat

I believe that excel does worksheets from index 1 not index 0

我相信 excel 从索引 1 而不是索引 0 做工作表

 var worksheet = package.Workbook.Worksheets[0]; 

should be

应该

var worksheet = package.Workbook.Worksheets[1];

to read the first worksheet.

阅读第一个工作表。

回答by BMaximus

Also, you can manage them by referencing the name:

此外,您可以通过引用名称来管理它们:

var worksheet = package.Workbook.Worksheets["Sheet1"];

回答by Paul Zahra

At least with Epplus 3.1.3.0 you can simply use the following to access the first worksheet.

至少在 Epplus 3.1.3.0 中,您可以简单地使用以下内容访问第一个工作表。

ExcelWorksheet workSheet = excel.Workbook.Worksheets.First();

回答by Alexander Shagin

Make sure the document created or saved with MS Excel (not OpenOffice, Libre Office, etc.)

确保使用 MS Excel 创建或保存的文档(不是 OpenOffice、Libre Office 等)