65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用连接字符串在 C# 中读取 Microsoft Excel 2007

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.52/5 (16投票s)

2007 年 11 月 28 日

CPOL

1分钟阅读

viewsIcon

283459

downloadIcon

11121

本文介绍了如何使用连接字符串连接到 Microsoft Excel 2007 并填充 DataGridView。

Screenshot - readExcel1.gif

引言

本文档介绍了如何使用 ADO.NET 连接字符串连接到 Microsoft Excel 2007,并在窗体上填充一个 DataGridView

Using the Code

首先,使用 Visual Studio 创建一个 C# Windows 应用程序。从工具箱中将以下控件添加到主窗体:

  • DataViewGrid 控件(命名为 dgvExcelList
  • BindingSource 控件(命名为 dataBindingSrc
  • Button 控件(命名为 btnPopulate

现在,打开 Microsoft Excel 2007 并输入一些记录。保存文件并关闭 Excel。

我已经创建了一个示例 Excel 2007 文件,该文件位于演示项目的项目文件夹中。如果您需要,可以通过复制到 C:\ 来使用它。Excel 文件的名称是 Members.xlsx

将以下代码复制到 btnPopulate_Click 事件中并运行应用程序。您会发现 dgvExcelList 填充了 Excel 文件 Sheet1 中的所有条目。

注意:如果您想使用自己的 Excel 文件,或者将 Members.xlsx 文件保存到 C:\ 以外的其他位置,请从连接字符串中更改文件和路径名称。

代码

// You can change C:\Members.xlsx to any valid path 
// where the file is located.

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
    FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
				Data Source=C:\Members.xlsx;Extended
    FONT-SIZE: 10pt; COLOR: #a31515; FONT-FAMILY: 'Courier New'">
				Properties=""Excel 12.0;HDR=YES;"""; 
// if you don't want to show the header row (first row) in the grid
// use 'HDR=NO' in the string

string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open(); // this will open an Excel file
OleDbCommand dbCommand = new OleDbCommand(strSQL,excelConnection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);

// create data table
DataTable dTable = new DataTable();

dataAdapter.Fill(dTable);

// bind the datasource
dataBingingSrc.DataSource = dTable;
// assign the dataBindingSrc to the DataGridView
dgvExcelList.DataSource = dataBingingSrc;

// dispose used objects
dTable.Dispose()
dataAdapter.Dispose();
dbCommand.Dispose();
excelConnection.Close();
excelConnection.Dispose();

欢迎提出您的建议和意见。

历史

  • 2007 年 11 月 28 日:初始发布
© . All rights reserved.