C# 中的 Microsoft Excel 客户端






2.98/5 (19投票s)
2005年12月8日
1分钟阅读

179109

3797
MicrosoftExcelClient 是一个用 C#.NET 编写的小型程序集,用于与 Excel 表格进行交互,即在 .NET Framework 中读取和写入 Excel 表格。
引言
在下面的文章中,简要描述了一个用于与 Microsoft Excel 文档进行交互的客户端。与 Excel 文档交互(读取、插入、更新等)是 ADO.NET 中的一项基本任务,每个开发人员都应该了解与 Excel 文档交互的知识。MicrosoftExcelClient
是一个简单的类,任何开发人员都可以在他们的代码中使用它来与 Excel 文档进行交互。它是在 C# 中创建的,并使用 OLEDB。
MicrosoftExcelClient 内部
MicrosoftExcelClient
是用 C# 创建的,本质上是一个类,它提供了一个易于使用的简单接口来访问 .NET Framework 中的 Excel 工作簿。OLEDB 组件在 C# 中用于像访问数据库一样访问 Excel 表格。
/// <summary>
/// Connects to the source excel workbook
/// </summary>
OleDbConnection m_ConnectionToExcelBook;
/// <summary>
/// Reads the data from the document to a System.Data object
/// </summary>
OleDbDataAdapter m_AdapterForExcelBook;
下面是 MicrosoftExcelClient 程序集中使用的一些基本函数的代码片段…
打开与 Excel 工作簿的连接
this.m_ConnectionToExcelBook =
new OleDbConnection("Provider=Microsoft.Jet" +
".OLEDB.4.0;Data Source=" +
this.m_SourceFileName +
";Extended Properties=Excel 8.0;");
this.m_ConnectionToExcelBook.Open();
从 Excel 表格读取数据
DataTable returnDataObject = new DataTable();
OleDbCommand selectCommand =
new OleDbCommand("select * from [" + iSheetName + "$]");
selectCommand.Connection = this.m_ConnectionToExcelBook;
this.m_AdapterForExcelBook = new OleDbDataAdapter();
this.m_AdapterForExcelBook.SelectCommand = selectCommand;
this.m_AdapterForExcelBook.Fill(returnDataObject);
插入或更新格式
OleDbCommand nonQueryCommand = new OleDbCommand(iQuery);
nonQueryCommand.Connection = this.m_ConnectionToExcelBook;
nonQueryCommand.CommandText = iQuery;
nonQueryCommand.ExecuteNonQuery();
如何使用 MicrosoftExcelClient
如前所述,提供的客户端对于初学者来说非常易于使用,对于经验丰富的专业人士来说应该非常简单。下面是一个简短的片段,展示了使用此程序集从 Excel 表格中提取和馈送数据的简单程度…
//Declare the sample object & set source data path
MicrosoftExcelClient sampleObject =
new MicrosoftExcelClient("SampleData.xls");
//Open connection to the excel work book
sampleObject.openConnection();
//Load the entire excel sheet into Datagrid1
//( Sheet name is passed as a parameter )
this.dataGrid1.DataSource = sampleObject.readEntireSheet("sheet1");
//Load the result of a specific query on the excel sheet into Datagrid2
//Query pased as a parameter
this.dataGrid2.DataSource =
sampleObject.readForSpecificQuery("select data1 , " +
"data2 ,data3 from [sheet1$]");
//******NON RESULT ORIENTED QUERIES*******
//Inserts a new record into the excel sheet
sampleObject.runNonQuery("insert into [sheet1$]" +
" values('1','2','3','4','5','6','7') ");
//Update the given excel sheet
sampleObject.runNonQuery("update [sheet1$] set data1 = '9'");
结论
总而言之,MicrosoftExcelClient
非常易于使用,并且是开源的,没有版权限制。您可以不受任何限制地按部分或整体使用它。演示项目没有错误,欢迎提出任何建议。在使用 NonQuery
函数从 Excel 数据库中删除记录时,您可能会遇到问题,但这归因于 OLEDB 的缺点,而不是代码中的错误。