Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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