C# Excel Instance


New Project, Console Application
References, Add Reference, Assemblies > Extensions
Add "Microsoft.Office.Interop.Excel"
Add the following code:

using Excel = Microsoft.Office.Interop.Excel; 

            try
            {
                Excel.Application oExcelApplication;
                Excel.Workbook oWorkbook;
                Excel.Worksheet oWorksheet;

                oExcelApplication = new Excel.Application();
               oExcelApplication.Visible = true;
                oWorkbook = oExcelApplication.Workbooks.Add();
                oWorksheet = oWorkbook.Sheets[1];
                oWorksheet.Name = "New Worksheet";

                for (long lRowNo = 1; lRowNo < 6; lRowNo++)
                {
                    oWorksheet.get_Range("A" + lRowNo).Value = lRowNo * 10;
                }
                oWorksheet.get_Range("A" + 6).Formula = "=SUM(A1:A5)";
                oWorkbook.SaveAs(@"C:\temp\MyFile.xlsx");

                oExcelApplication.Quit();
            }
            catch(System.Runtime.InteropServices.COMException ex)
            {
                Console.WriteLine(ex.ErrorCode.ToString() + " - " + ex.Message);
            }

Select (Build > Build Solution)
Run



© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext