日期:2014-05-20 浏览次数:21239 次
private void MenuItem_Click(object sender, RoutedEventArgs e)//菜单点击事件
{
MenuItem mn=sender as MenuItem;
string openExcelFilename="";
string connectionString = "";
switch(mn.Header.ToString())//比较选取的菜单标题
{
case "Excel97-2003文件"://如果是"Excel97-2003文件"
OpenFileDialog fileOpenExcel03 = new OpenFileDialog();\\执行打开文件对话框
fileOpenExcel03.Filter = "Excel文件97-2003(*.xls)|*.xls";
if (fileOpenExcel03.ShowDialog() != true)
return;
openExcelFilename = fileOpenExcel03.FileName.Trim();
dbFilenameExcel = fileOpenExcel03.SafeFileName;
connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+openExcelFilename + ";Extended Properties='Excel 8.0'";\\根据打开的文件生成连接字符串
break;
case "Excel2007-10文件"://如果是"Excel2007-10文件"
OpenFileDialog fileOpenExcel07 = new OpenFileDialog();\\执行打开文件对话框
fileOpenExcel07.Filter = "Excel2007-10文件(*.xlsx)|*.xlsx";
if (fileOpenExcel07.ShowDialog() != true)
return;
openExcelFilename = fileOpenExcel07.FileName.Trim();
dbFilenameExcel = fileOpenExcel07.SafeFileName;
connectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+openExcelFilename + ";Extended Properties='Excel 12.0'";\\根据打开的文件生成连接字符串
break;
}
OleDbConnection ODCExcel = new OleDbConnection(connectionString);//创建连接
SelectWindow selectWin = new SelectWindow();//构造了一个新窗体
List<string> tableNames = GetTableNames(ODCExcel);//这句话用来获取Excel文件的表名
if (tableNames.Count <= 0)
return;
selectWin.cmbTableList.Items.Clear();//清空新窗体上名为cmbTableList的ComboBox的内容
selectWin.cmbTableList.ItemsSource = tableNames;//把获取的表名加入到ComboBox中
if (selectWin.ShowDialog() != true)
return;
tableNameExcel = "[" + selectWin.cmbTableList.Text + "]";
DataSet dsExcel=new DataSet();
string selectString = "select * From " + tableNameExcel;
OleDbDataAdapter ODCAExcel = new OleDbDataAdapter(selectString, ODCExcel);
try
{
ODCAExcel.Fill(dsExcel, "tableOpening");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private List<string> GetTableNames(System.Data.Common.DbConnection dbConnection)
{
List<string> tableNames = new List<string>();
try
{
dbConnection.Open();
System.Data.DataTable schema = dbConnection.GetSchema("Tables");
foreach (System.Data.DataRow r in schema.Rows)
{
tableNames.Add((string)r["Table_Name"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dbConnection.Close();
}
return tableNames;
}