Friday, 8 July 2011

How to read and write Word/Excel 2007 files from C# programs?

(1) Add following references to your VS2008 project:
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

full spec of above packages can be found at:
Microsoft.Office.Interop.Word Namespace
Microsoft.Office.Interop.Excel Namespace

Alternatively, you can use the 'object browser' from VS2008 or F1 key online help

(2) create following object in your C# programs and work on them:
object oMissing = System.Reflection.Missing.Value;
Excel.Application oXL = new Excel.Application();
Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks._Open("my_workbook.xlsx", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing));
Excel._Worksheet oSheet = (Excel._Worksheet)oWB.Sheets["my_sheet"];
Excel.Range oRng = oSheet.UsedRange;

Word._Application oWord = new Word.Application();
Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oDoc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;
oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;
oDoc.PageSetup.LeftMargin = oWord.MillimetersToPoints(15F);
oDoc.PageSetup.RightMargin = oWord.MillimetersToPoints(15F);
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
Word.Table oTable = oDoc.Tables.Add(wrdRng, 1, num_of_cols, ref oMissing, ref oMissing);

(3) clean the objects afterward:
object oDoNotSave = Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref oDoNotSave, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
oWB.Close(oMissing, oMissing, oMissing);
oXL.Quit();