Search code examples
excelexcel-2007xlsxnamed-rangesspreadsheetlight

Why is my "defined name" (range) value not being set with this Spreadsheet Light code?


I've got this code to apply a "header" (big, top-of-the-sheet "title") to a sheet:

// Initialize
private static SLDocument sl;
. . .
sl = new SLDocument();

// Create a Style
SLStyle styleHeading = sl.CreateStyle();
styleHeading.SetFont(FontSchemeValues.Major, 36);
styleHeading.Font.Italic = true;
styleHeading.Font.FontName = "Candara";

// Create a Defined Name (Range) and give it a value and style
sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13"); 
sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
sl.SetCellStyle("UnitName", styleHeading);

// Save the sheet
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
string spreadsheetLightFilename = "PlatypiTest.xlsx";
string fullspreadsheetLightPath = Path.Combine(appDataFolder, spreadsheetLightFilename);
sl.SaveAs(fullspreadsheetLightPath);

Note: I verified that "Sheet1" was right with this code:

var nameList = sl.GetSheetNames();
string s = nameList[0]; // "s" is "Sheet1"

The file is created and saved, but it is devoid of content; when I open it, cell A1 is highlighted, but is content-free.

Am I missing a vital step, or going about this completely wrong?


Solution

  • What are you doing is logically fine.

    This line

    sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13"); 
    

    indeed creates a named range. You can see it if you open the resulting file in Excel and look at the cell selector:

    enter image description here

    or the Name Manager:

    enter image description here

    The problem is though that Spreadsheet Light has a very basic support for Defined names - basically all you can do is to create a name and use it inside the formulas. All methods that manipulate content expect single cell reference. Btw, all these methods do not throw exception if you don't pass a valid cell reference, but return bool indicating success/failure.

    For instance, if you change your code to

    bool success1 = sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
    bool success2 = sl.SetCellStyle("UnitName", styleHeading);
    

    you will see that both success variables are false.

    Shortly, if you want to bring some content to the Excel file, you should do it cell by cell. It even does not support regular (unnamed) ranges.