Friday, September 12, 2008

Create Word, Excel using Office Object Library

Add a reference to Microsoft Word Object XX.0 Library and also same for Excel. i have user Object Library 12.0

using MSWord Microsoft.Office.Interop.Word;
using MSExcel = Microsoft.Office.Interop.Excel;

public bool CreateWordDocument(string FilePath)
{
bool bsuccess = false;
try
{
object missing = System.Reflection.Missing.Value;
MSWord.ApplicationClass msword = new MSWord.ApplicationClass();
Document doc = msword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
object Filename = FilePath;
doc.SaveAs(ref Filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
bsuccess = true;
}
catch
{
bsuccess = false;
}
return bsuccess;
}

public bool CreateExcelWorkBook(string FilePath)
{
bool bsuccess = false;
try
{
object missing = System.Reflection.Missing.Value;
MSExcel.ApplicationClass excel = new MSExcel.ApplicationClass();
MSExcel.Workbook book = excel.Workbooks.Add(missing);
object Filename = FilePath;
book.SaveAs(Filename, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
excel.Quit();
bsuccess = true;
}
catch
{
bsuccess = false;
}
return bsuccess;
}