2017-02-21 126 views
1

我想從Excel中的文件讀取數據,但出於某種原因出錯。這是我在做什麼:如何從Excel文件讀取數據?

Excel.Application xlApp ; 
Excel.Workbook xlWorkBook ; 
Excel.Worksheet xlWorkSheet ; 
Excel.Range range ; 

string str; 
int rCnt ; 
int cCnt ; 
int rw = 0; 
int cl = 0; 

xlApp = new Excel.Application(); 
xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\pc\Desktop\Alessio.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); 
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 

range = xlWorkSheet.UsedRange; 
rw = range.Rows.Count; 
cl = range.Columns.Count; 


for (rCnt = 1; rCnt <= rw; rCnt++) 
{ 
    for (cCnt = 1; cCnt <= cl; cCnt++) 
    { 
     str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2; 
     MessageBox.Show(str); 
    } 
} 

,這是例外,我得到:

"System.Runtime.InteropServices.COMException' in WindowsFormsApplication2.exe" 
Adding information:HRESULT: 0x80010105 (RPC_E_SERVERFAULT) 

你知道爲什麼,我該如何解決這個問題?

+1

運行時錯誤在哪裏?嘗試使用F10進行調試並查看地點。與此同時,嘗試:'str = range.Cells [rCnt,cCnt] .Value2;' – Vityata

+1

當我嘗試執行下面的代碼行時,我得到異常:「xlWorkBook = xlApp.Workbooks.Open(@」C:\ Users \ pc \ Desktop \ Alessio.xls「,0,true,5,」「,」「,true,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,」\ t「,false,false,0,true, 1,0);「 – Ale

回答

1

這不是一個編碼問題。嘗試刪除項目中的Microsoft.Office.Interop.Excel/Office參考,並使用相關版本號重新加載。

+0

嗨,你是什麼意思? – Ale

+0

請查看https://msdn.microsoft.com/en-us/library/dd264733.aspx – sofsntp

0

你可以把所有東西放在DataGridView中。

using System; 
using System.Drawing; 
using System.Windows.Forms; 
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       System.Data.OleDb.OleDbConnection MyConnection ; 
       System.Data.DataSet DtSet ; 
       System.Data.OleDb.OleDbDataAdapter MyCommand ; 
       MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;"); 
       MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection); 
       MyCommand.TableMappings.Add("Table", "TestTable"); 
       DtSet = new System.Data.DataSet(); 
       MyCommand.Fill(DtSet); 
       dataGridView1.DataSource = DtSet.Tables[0]; 
       MyConnection.Close(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show (ex.ToString()); 
      } 
     } 
    } 
}