62,046
社区成员
发帖
与我相关
我的任务
分享
public partial class MainWindow : Window
{
DataSet dsExcel= new DataSet();
string dbFilenameExcel;
string tableNameExcel;
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem mn=sender as MenuItem;
string openExcelFilename="";
string connectionString = "";
switch(mn.Header.ToString())
{
case "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文件":
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);
if (tableNames.Count <= 0)
return;
selectWin.cmbTableList.Items.Clear();
selectWin.cmbTableList.ItemsSource = tableNames;
if (selectWin.ShowDialog() != true)
return;
tableNameExcel = "[" + selectWin.cmbTableList.Text + "]";
string selectString = "select * From " + tableNameExcel;
OleDbDataAdapter ODCAExcel = new OleDbDataAdapter(selectString, ODCExcel);
try
{
dsExcel.Clear();
ODCAExcel.Fill(dsExcel, "tableOpening");
dataGridExcel.ItemsSource = dsExcel.Tables["tableOpening"].DefaultView;
lblMessage.Content = openExcelFilename + ":" + tableNameExcel.Substring(1, tableNameExcel.Length - 3);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//以下省略