/// <summary>
/// 获取选定Excel文件的工作表列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button1_Click(object sender, System.EventArgs e)
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source="+ SelectFile.Value+";"+
"Extended Properties=Excel 8.0;";
TextBoxSelectedFile.Text = SelectFile.Value;
oleDbConnection.ConnectionString = strConn;
if(oleDbConnection.State ==ConnectionState.Closed)
oleDbConnection.Open();
ListBoxWorkSheets.DataSource = GetTableNames();
ListBoxWorkSheets.DataBind();
oleDbConnection.Close();
oleDbConnection.Dispose();
}
/// <summary>
/// 浏览选定的工作表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonBrowse_Click(object sender, System.EventArgs e)
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source="+ TextBoxSelectedFile.Text+";"+
"Extended Properties=Excel 8.0;";
string sql = "SELECT * FROM ["+ListBoxWorkSheets.SelectedItem.ToString()+"]";
if(oleDbConnection.State ==ConnectionState.Open)
oleDbConnection.Close();
OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(sql,strConn);
DataSet dataSet = new DataSet();
DataGrid1.DataSource = null;
oleDbDataAdapter.TableMappings.Clear();
oleDbDataAdapter.Fill(dataSet);
DataGrid1.DataSource = dataSet;
DataGrid1.DataBind();
}
/// <summary>
/// 获取指定Excel文件的工作表列表
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private ArrayList GetTableNames()
{
if(oleDbConnection.State ==ConnectionState.Closed)
oleDbConnection.Open();
DataTable dt = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
ArrayList tables = new ArrayList();
for(int i = 0;
i < dt.Rows.Count;
i ++)
{
tables.Add(dt.Rows["TABLE_NAME"]);
}
return tables;
}