Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To read/write from excel spreadsheet using C#

Tags:

c#

database

excel

I need to make a program that writes some data to an excel spreadsheet. Something basic along the lines of First name, last name, phone number, e-mail per row with each category in its own column.

I don't even know where to start. If someone could tell me which assemblies to reference and maybe point me to a website or a book that covers writing/reading data from an excel spreadsheet via a C# program that would be great.

Many thanks.

like image 387
Aaron Avatar asked Aug 06 '26 23:08

Aaron


2 Answers

Add a reference to Microsoft.Office.Interop.Excel.

Assuming you have a repository of that data somewhere, and your model looks something like

class Contact
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

you can import it into excel like this

Application excelapp = new Application();
excelapp.Visible = true;

_Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));
_Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

worksheet.Cells[1, 1] = "First Name";
worksheet.Cells[1, 2] = "Last Name";
worksheet.Cells[1, 3] = "Email";
worksheet.Cells[1, 4] = "Phone Number";

int row = 1;

foreach (var contact in contacts)
{
    row++;

    worksheet.Cells[row, 1] = contact.Firstname;
    worksheet.Cells[row, 2] = contact.Lastname;
    worksheet.Cells[row, 3] = contact.Email;
    worksheet.Cells[row, 4] = contact.PhoneNumber;
}

excelapp.UserControl = true;

You can read more about the Excel interop library here: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel%28v=office.11%29.aspx

like image 152
Chris Almond Avatar answered Aug 08 '26 11:08

Chris Almond


This particular feature is called "Excel Automation" in .NET where you can use C# to manipulate your spreadsheet.

A good starting point will be, http://support.microsoft.com/kb/302084#top

Regards, Andy.

like image 30
drhanlau Avatar answered Aug 08 '26 11:08

drhanlau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!