Pregunta

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.

¿Fue útil?

Solución

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";
            }
        }

Otros consejos

A couple of notes. First, you do not have an active sheet because you have not created one, and Excel will not create one by default.

Try the (simplified) code in your button click event handler:

Excel.Workbook workbook = _excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Worksheets[0];
worksheet.PageSetup.CenterFooter = filename;
// Do remaining work here

Also, the line

var filename = _excelApp.GetSaveAsFilename();

Only returns the filename selected by the user. It does not actually save the file. You will need to follow it up with:

workbook.SaveAs(Filename: filename);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top