Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus, Find and set the value for a Named Range

Tags:

c#

excel

epplus

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:

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

like image 997
BigBadOwl Avatar asked Jul 04 '12 15:07

BigBadOwl


2 Answers

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.

I suggest you use EPPlus wich is a excel library (xlsx only) that have worked great to me.

official link

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";                        
        }
    }
}
like image 95
daniloquio Avatar answered Oct 12 '22 16:10

daniloquio


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); }
                }
like image 21
BigBadOwl Avatar answered Oct 12 '22 17:10

BigBadOwl