使用C#从excel电子表格中读/写 [英] To read/write from excel spreadsheet using C#

查看:125
本文介绍了使用C#从excel电子表格中读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个将一些数据写入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆