How can I read data from an Excel file?

2

I am trying to read data from a file in Excel but for some reason something goes wrong. This is what I am doing:

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);
    }
}

And this is the exception I get:

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

Do you know why I have and how I can solve this problem?

c#
excel
asked on Stack Overflow Feb 21, 2017 by Ale • edited Jul 8, 2019 by Matt Ellen

2 Answers

1

it's not a coding issue. Try to remove the Microsoft.Office.Interop.Excel / Office reference in your project and reload the one with the relevant version number.

answered on Stack Overflow Feb 21, 2017 by sofsntp
0

You can put everything in a 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());
            }
        }
   }
}
answered on Stack Overflow Feb 23, 2017 by ASH

User contributions licensed under CC BY-SA 3.0