我如何从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) 

你知道为什么以及如何解决这个问题吗?

这不是一个编码问题。 尝试删除项目中的Microsoft.Office.Interop.Excel / Office引用,并使用相关版本号重新加载。

你可以把所有东西放在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()); } } } }