请问如何用C#读到一个EXCEL表中sheet的数量和它们的名称(100分)

  • 主题发起人 主题发起人 wphmoon
  • 开始时间 开始时间
W

wphmoon

Unregistered / Unconfirmed
GUEST, unregistred user!
我用C#开发一个读取excel表中数据的程序,其中有家庭用户资料,各个家庭用户的数量不同,
一个家庭成员用一个sheet,所以事先不知道表中有多少个sheet,请问如何解决这个问题,读到表中
的sheet数量和名称
 
officePIA,到msdn上去下吧,很好用,微软真的很可怕[8D].
 
/// <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;
}
 
后退
顶部