打开指定的Excel表格——Visual C#读取Excel和Access数据库

Visual C#读取ExcelAccess数据库

三峡大学土木水电学院 肖泽云

Content

一、读取Excel表格... 1

二、保存Excel文件... 5

三、获取表的名称... 6

四、打开指定的Excel表格... 8

五、读取Access数据库... 10

六、获取Access表信息... 12

七、打开指定的Access... 13

四、打开指定的Excel表格

前面使用的Oledb方式以及App方式都是打开Excel文件中的第一个表格或已知表名的表格,如果在不知道Excel文件中表名的情况下要查看Excel文件中表格,则可以结合前面获取Excel表格信息,来通过指定表名的方式打开指定表格。

首先,添加一个按钮,设置其Name为“打开Excel文件button”,Text为“打开Excel文件”;再添加一个按钮,设置其Name为“打开指定的Excel表格button”,Text为“打开指定的Excel表格”;添加一个ComboBox控件,设置其Name为“ExcelComboBox”。如下图所示:

打开指定的Excel表格——Visual C#读取Excel和Access数据库

1、打开Excel文件

由于是通过Oledb的方式来打开Excel文件,所以需要在全局变量中定义:

private OleDbConnection excelOledbConnection;

在打开Excel文件时,将获取到的Excel文件中表格名称全部用ComboBox控件列表显示出来,所以在“打开Excel文件button”按钮的Click事件中添加如下代码:

private void 打开Excel文件button_Click(object sender, EventArgs e)

{

OpenFileDialog openDG = new OpenFileDialog();

openDG.Title = "打开Excel表格";

openDG.Filter = "Excel表格(*.xls)|*.xls|CSV格式(*.csv)|*.csv|所有文件(*.*)|*.*";

openDG.ShowDialog();

string filename;

filename = openDG.FileName;

string strConn

= @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";

excelOledbConnection = new OleDbConnection(strConn);

excelOledbConnection.Open();

DataTable table = new DataTable();

table = excelOledbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

ExcelComboBox.Items.Clear();

foreach (DataRow dataRow in table.Rows)

{

ExcelComboBox.Items.Add((String)dataRow["TABLE_NAME"]);

}

ExcelComboBox.Text = ExcelComboBox.Items[0].ToString();

}

2、打开指定的Excel表格

根据ComboBox控件中选中的表格名称来打开该表格,在“打开指定的Excel表格button”的Click事件中添加如下代码:

private void 打开指定的Excel表格button_Click(object sender, EventArgs e)

{

OleDbCommand odCommand = excelOledbConnection.CreateCommand();

odCommand.CommandText = "SELECT * FROM [" + ExcelComboBox.Text + "]";

OleDbDataReader odrReader = odCommand.ExecuteReader();

int size = odrReader.FieldCount;

dataGridView1.Columns.Clear();

//添加列的名称

for (int i = 0; i < size; i++)

{

dataGridView1.Columns.Add("", odrReader.GetName(i));

}

int j = 0;

while (odrReader.Read())

{

dataGridView1.Rows.Add();

for (int i = 0; i < size; i++)

{

dataGridView1.Rows[j].Cells[i].Value = odrReader[i].ToString();

}

j++;

}

}

其结果如下图所示:

打开指定的Excel表格——Visual C#读取Excel和Access数据库