Created
May 16, 2013 09:37
-
-
Save mdelanno/5590594 to your computer and use it in GitHub Desktop.
Write in an Excel cell from an application written in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace WriteToExcel | |
{ | |
class Program | |
{ | |
const string EXCEL_PROG_ID = "Excel.Application"; | |
const uint MK_E_UNAVAILABLE = 0x800401e3; | |
const uint DV_E_FORMATETC = 0x80040064; | |
static void Main(string[] args) | |
{ | |
dynamic excelApp = null; | |
try | |
{ | |
excelApp = Marshal.GetActiveObject(EXCEL_PROG_ID); | |
} | |
catch (COMException ex) | |
{ | |
switch ((uint)ex.ErrorCode) | |
{ | |
case MK_E_UNAVAILABLE: | |
case DV_E_FORMATETC: | |
// Excel n'est pas lancé. | |
break; | |
default: | |
throw; | |
} | |
} | |
if (null == excelApp) | |
excelApp = Activator.CreateInstance(Type.GetTypeFromProgID(EXCEL_PROG_ID)); | |
if (null == excelApp) | |
{ | |
Console.Write("Unable to start Excel"); | |
return; | |
} | |
excelApp.Visible = true; | |
dynamic workbook = excelApp.ActiveWorkbook ?? excelApp.Workbooks.Add(); | |
dynamic sheet = workbook.ActiveSheet; | |
dynamic cell = sheet.Cells[1, 1]; | |
cell.Value = "Hello world!"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment