C# EPPlus,查找并设置命名范围的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11332326/
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
EPPlus, Find and set the value for a Named Range
提问by BigBadOwl
I've been pulling my hair out trying to set the value of a named range (in this case, a single named cell) using the ExcelPackage (3.0.1) library, it should be a simple as this:
我一直在尝试使用 ExcelPackage (3.0.1) 库设置命名范围(在本例中为单个命名单元格)的值,它应该是这样简单:
ExcelNamedRange er = xlPackage.Workbook.Names["Customer"];
er.Value = "Foo Bar";
I'm obviously doing it wrong - has anyone got an example I can follow
我显然做错了 - 有没有人有我可以效仿的例子
Thanks
谢谢
回答by BigBadOwl
I had to put in a work around using a cell value instead.
我不得不改用单元格值来解决。
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
foreach (ExcelWorksheet worksheet in xlPackage.Workbook.Worksheets)
{
var dimension = worksheet.Dimension;
if (dimension == null) { continue; }
var cells = from row in Enumerable.Range(dimension.Start.Row, dimension.End.Row)
from column in Enumerable.Range(dimension.Start.Column, dimension.End.Column)
//where worksheet.Cells[row, column].Value.ToString() != String.Empty
select worksheet.Cells[row, column];
try
{
foreach (var excelCell in cells)
{
try
{
if (excelCell.Value.ToString().Equals("[Customer]")) { excelCell.Value = "Customer Name"; }
}
catch (Exception) { }
}
}
catch (Exception a) { Console.WriteLine(a.Message); }
}
回答by daniloquio
I looked for ExcelPackage documentation to see what type Names[] collection returns and found that documentatios will come soon, or at least that is what they said back in 2007.
我查找 ExcelPackage 文档以查看 Names[] 集合返回的类型,并发现文档很快就会出现,或者至少这是他们在 2007 年所说的。
I suggest you use EPPlus wich is a excel library (xlsx only) that have worked great to me.
我建议您使用 EPPlus,它是一个对我非常有用的 excel 库(仅限 xlsx)。
Now, to set a value for each cell in a named range:
现在,为命名范围内的每个单元格设置一个值:
ExcelWorksheet sheet = _openXmlPackage.Workbook.Worksheets["SheetName"];
using (ExcelNamedRange namedRange = sheet.Names["RangeName"])
{
for (int rowIndex = Start.Row; rowIndex <= namedRange.End.Row; rowIndex++)
{
for (int columnIndex = namedRange.Start.Column; columnIndex <= namedRange.End.Column; columnIndex++)
{
sheet.Cells[rowIndex, columnIndex].Value = "no more hair pulling";
}
}
}

