Search code examples
c#excel-2010excel-addins

How to set Excel footer with Excel-Add-In


I've been told to write up an Excel-Add-In which pastes a specific footer into every worksheet in a workbook.

After reading up the documentation of the Excel.Interop namespace I ended up with this junky piece of code:

 public partial class Ribbon1
{
    Excel.Application _excelApp;
    private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
    {
        _excelApp = new Excel.Application();
    }

    private void button1_Click(object sender, RibbonControlEventArgs e)
    {
        var filename = _excelApp.GetSaveAsFilename();
        Excel._Worksheet worksheet = (Excel._Worksheet)_excelApp.ActiveSheet;
        worksheet.PageSetup.CenterFooter = filename;
    }
}

I have a problem in pinning the active worksheet. How can I actually use this object? - Right now it is null. I find the msdn articles related to this topic just plain stupid.


Solution

  • I finally found the information I was looking for at: VSTO

    First of all I set those 2 lines:

    using Excel = Microsoft.Office.Interop.Excel;
    using Office = Microsoft.Office.Tools.Excel;
    

    As a second step I check if the workbook is not null, then if the worksheet is not null. If this is the case, set the footer to the document. It is not pretty, but I can refine it tommorow at the office.

    Excel.Workbook Workbook = Globals.ThisAddIn.Application.ActiveWorkbook;
            if (Workbook != null)
            {
                Office.Workbook vstoWorkbook = Globals.Factory.GetVstoObject(Workbook);
    
                Excel.Worksheet worksheet = Globals.ThisAddIn.Application.ActiveSheet;
                if (worksheet != null)
                {
                    Office.Worksheet vstoSheet = Globals.Factory.GetVstoObject(worksheet);
                    vstoSheet.PageSetup.CenterFooter = "testing the footer";
                }
            }