George Perkins George Perkins - 8 months ago 51
C# Question

Linking Excel In c#

So i'm working in Microsoft Visual Studio 2015 and want to be able to link the project to a Excel Spreadsheet.

What I want to achieve is this; simply be able to create a program where I can use the number in a specific cell and then do some calculations with it. As an example, take cell D4 and then create a poisson distribution using the value as the mean.



You need to add a reference to Microsoft.Office.Core and Microsoft.Office.Interop.Excel in the projects References. Then add the references to your class.

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

Then you can open/create/manipulate excel sheets in your code. lots of info for that on the web.

Update to comment--

This example is opening a new worksheet to save when done.

Excel.Application xlApp;
Excel.Workbook myWorkBook;
Excel.Worksheet myWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
myWorkBook = xlApp.Workbooks.Add(misValue);
myWorkSheet =  (Excel.Worksheet)myWorkBook.Worksheets.get_Item(1);

Done some work on the sheet

myWorkSheet.Cells[curXLRow, 5] = "PF";
myWorkSheet.Cells[curXLRow, 6] = "PA";

Then Save the file

string fileName = "C:\\MyFileName.xlsx";
myWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
myWorkBook.Close(true, misValue, misValue);


Hope this helps. I dont have an example to open an existing excel file. But look up:

xlApp.Workbooks.Open(lots of parameters...);