interface with excel in csharp

To interface with Excel in C#, you can use the Microsoft Office Interop library, which allows you to automate Excel using COM technology.

Here are the basic steps to get started:

  1. Add a reference to the Microsoft.Office.Interop.Excel assembly in your project.

  2. Create a new instance of the Application class:

main.cs
using Microsoft.Office.Interop.Excel;

// ...

var excel = new Application();
78 chars
6 lines
  1. Open an Excel workbook:
main.cs
var workbook = excel.Workbooks.Open(@"C:\path\to\my\workbook.xlsx");
69 chars
2 lines
  1. Get a reference to a specific worksheet:
main.cs
var worksheet = (Worksheet)workbook.Worksheets["Sheet1"];
58 chars
2 lines
  1. Read or write data in the worksheet:
main.cs
// Read a cell value
var value = worksheet.Range["A1"].Value;

// Write a cell value
worksheet.Range["A1"].Value = "Hello, world!";
132 chars
6 lines
  1. Save and close the workbook:
main.cs
workbook.Save();
workbook.Close();
35 chars
3 lines

It's important to note that when automating Excel, you should always release the COM objects you use when you're done with them, to avoid memory leaks. Here's an example:

main.cs
// Release the worksheet COM object
Marshal.ReleaseComObject(worksheet);

// Release the workbook COM object
Marshal.ReleaseComObject(workbook);

// Release the Excel Application COM object
Marshal.ReleaseComObject(excel);
223 chars
9 lines

gistlibby LogSnag