To read/write from excel spreadsheet using C#

20,111

Solution 1

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

Solution 2

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.

Solution 3

Depending on the level of sophistication needed:

  • Write a comma-separated values (CSV) text file. Excel will open it, however you wont get any formatting.
  • Write an HTML table to file and name the file as filename.xls.
  • Write out an XML file in a format that Excel can open.
  • Call Excel directly and get it to build the spreadsheet. (See cherhan's answer)
Share:
20,111
Aaron
Author by

Aaron

Updated on July 10, 2022

Comments

  • Aaron
    Aaron almost 2 years

    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.