Search code examples
.netms-wordms-officedocumentfooter

Programmatically add footer to Office Word/Excel document


I'm looking to build a solution similar to this one: http://esqinc.com/section/products/4/idocid.html

What the system makes is insertion of a document file name into the document footer. How's that possible programmatically (preferably in .NET)?


Solution

  • I just happened to be working on code where I already do this in Excel from C#... This is partial, and will get you started...

    Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
    excelapp.Visible = true;
    Microsoft.Office.Interop.Excel._Workbook book = (Microsoft.Office.Interop.Excel._Workbook)excelapp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); ;
    Microsoft.Office.Interop.Excel._Worksheet sheet = (Microsoft.Office.Interop.Excel._Worksheet)book.ActiveSheet;
    
    
    sheet.get_Range("A1", "N999").Font.Size = "8";
    sheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperLegal;
    sheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
    sheet.PageSetup.PrintTitleRows = "$3:$5";
    sheet.PageSetup.PrintTitleColumns = "$A:$B";
    

    There's more code there than you need for this specific task, but the relevant lines for having a header (or something that repeats at the top of each page) are:

    sheet.PageSetup.PrintTitleRows = "$3:$5";
    sheet.PageSetup.PrintTitleColumns = "$A:$B";
    

    Edit - Added

    Here's a link to MSDN documentation, for all your Office Interop needs.

    http://msdn.microsoft.com/en-us/library/bb209015(office.12).aspx