Skip to content

Instantly share code, notes, and snippets.

@mdelanno
Created May 16, 2013 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdelanno/5590594 to your computer and use it in GitHub Desktop.
Save mdelanno/5590594 to your computer and use it in GitHub Desktop.
Write in an Excel cell from an application written in C#
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