2014-01-14 94 views
0
public void LoadExcel_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog fileDLG = new OpenFileDialog(); 
    fileDLG.Title = "Open Excel File"; 
    fileDLG.Filter = "Excel Files|*.xls;*.xlsx"; 
    fileDLG.InitialDirectory = @"C:\Users\...\Desktop\"; 

    if (fileDLG.ShowDialog() == DialogResult.OK) 
    { 
     string filename = System.IO.Path.GetFileName(fileDLG.FileName); 
     string path = System.IO.Path.GetDirectoryName(fileDLG.FileName); 
     excelLocationTB.Text = @path + "\\" + filename; 
     string ExcelFile = @excelLocationTB.Text; 
     if (!File.Exists(ExcelFile)) 
      MessageBox.Show(String.Format("File {0} does not Exist", ExcelFile)); 

     OleDbConnection theConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 12.0;"); 
     theConnection.Open(); 
     OleDbDataAdapter theDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", theConnection); 
     DataSet DS = new DataSet(); 
     theDataAdapter.Fill(DS, "ExcelInfo"); 
     dataGridView1.DataSource = DS.Tables["ExcelInfo"]; 
     formatDataGrid(); 
     MessageBox.Show("Excel File Loaded"); 
     toolStripProgressBar1.Value += 0; 
    } 
} 

好的,我從微軟得到了這段代碼。OleDbException未處理;超出系統資源

theDataAdapter.Fill(DS, "ExcelInfo"); 

這是給我的錯誤。

基本上這段代碼應該使用對話框來打開文件並將其顯示在窗體上。每當我打開一個Excel文件,它會給我這個錯誤。我甚至嘗試創建一個空白的Excel文件,它仍然給了我這個。

+0

我面臨着類似的問題,只是想分享一下觀察。當我打開excel文件時,點擊啓用編輯並再次點擊保存。讀取相同的文件時沒有錯誤。 –

回答

1

修改您的代碼。添加OleDbCommand來執行查詢選擇。你試一試。

OleDbConnection theConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Projects\Demo\Demo.xls;Extended Properties=Excel 8.0;"); 
     theConnection.Open(); 
     OleDbCommand theCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", theConnection); 
     OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(theCmd); 
     DataSet DS = new DataSet(); 
     theDataAdapter.Fill(DS); 
     theConnection.Close(); 
+0

它仍然給我同樣的錯誤:( – puretppc

+0

你檢查了你的連接嗎?它的配置是否正確? –

+0

你如何檢查連接? – puretppc