使用C#读取Excel电子表格/写 [英] Using C# to read/write from excel spreadsheet
问题描述
我需要做一些数据写入到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.
我甚至不知道从哪里开始。如果有人能告诉我哪些程序集引用,也许指向我一个网站或一本书,从通过C#程序的Excel电子表格,这将是巨大的占地面积读/写数据。
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.
非常感谢。
推荐答案
添加到的Microsoft.Office.Interop.Excel的引用。
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; }
}
您可以将其导入到Excel这样
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;
您可以阅读更多有关Excel互操作库在这里:的 http://msdn.microsoft.com/en-us/library/microsoft.office。 interop.excel%28V = office.11%29.aspx
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
这篇关于使用C#读取Excel电子表格/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!