Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

How to use openfiledialog to open an excel file c#

$
0
0

Hello everyone,

I'm trying to open an Excel file in c# winforms using the openfiledialog tool. The file should be shown in a datagridview. Here is what I have come up with. I'm not sure if it is right though. When I run it, the error "Input array is longer than the number of columns in this table." will appear at one of the lines below. Please help! 

        private void button7_Click(object sender, EventArgs e)
        {
            string delimiter = ",";
            string tablename = "medTable";
            DataSet dsPatent = new DataSet();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "xlsx Files (*.xlsx)|*.xlsx|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filename = openFileDialog1.FileName;
                StreamReader sr = new StreamReader(filename);
                string xlsx = File.ReadAllText(openFileDialog1.FileName);
                dsPatent.Tables.Add(tablename);
                dsPatent.Tables[tablename].Columns.Add("Invention Title");

                string allData = sr.ReadToEnd();
                string[] rows = allData.Split("\r".ToCharArray());
                foreach(string r in rows)
                {
                    string[] items = r.Split(delimiter.ToCharArray());
                    dsPatent.Tables[tablename].Rows.Add(items);   (error at this line)
                }
                this.dgPatent.DataSource = dsPatent.Tables[0].DefaultView;
            }
            else
            {
                this.Close();
            }

         }      
            public string filename { get; set; }

Thank you!


Viewing all articles
Browse latest Browse all 2535

Trending Articles