0

I have the code below to import value from excel to datagridview. But i want only the first row which is the header to be arranged vertically down in one column only. Here is the code. I have tried using something like dtExcel.Rows[0][0].ToString(); but it doesn't work. Can someone tell me why and how can i achieve this?

        private void button1_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        string fileExt = string.Empty;
        OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file  
        if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user  
        {
            filePath = file.FileName; //get the path of the file  
            fileExt = Path.GetExtension(filePath); //get the file extension  
            if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
            {
                try
                {
                    DataTable dtExcel = new DataTable();
                    dtExcel = ReadExcel(filePath, fileExt); //read excel file  
                    dataGridView1.Visible = true;
                    dataGridView1.DataSource = dtExcel;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
            else
            {
                MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error  
            }
        }  
    }

    public DataTable ReadExcel(string fileName, string fileExt)
    {
        string conn = string.Empty;
        DataTable dtexcel = new DataTable();
        if (fileExt.CompareTo(".xls") == 0)
            conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007  
        else
            conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel 2007  
        using (OleDbConnection con = new OleDbConnection(conn))
        {
            try
            {
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1  
                oleAdpt.Fill(dtexcel); //fill excel data into dataTable  
            }
            catch { }
        }
        return dtexcel;
    }  
5
  • What is the code of ReadRxcel? Commented Jun 16, 2016 at 6:51
  • @Kason Sorry, i didn't notice. I have included the code. Thank you Commented Jun 16, 2016 at 6:56
  • Enumerate through dtexcel.Columns() and get Name property : foreach (DataColumn col in dtexcel.Columns) Commented Jun 16, 2016 at 7:02
  • @jdweng Thank you for the reply. I will try it now Commented Jun 16, 2016 at 7:05
  • @Kason it's not necessarily A1. To be more specific the first row of excel a.k.a the header Commented Jun 16, 2016 at 7:06

2 Answers 2

1
 foreach (DataRow row in dtexcel.Rows) {
    for (int i = 0; i < dtexcel.Columns.Count;i++ )
       MessageBox.Show(row[i].ToString()); // row[i] is what you want.
    }

This code can help you check all the records in the table.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I manage to done something similar and get the value of the header. Many thanks again!
0

The header row you can get iterating through:

string[] columnName = new string[dtexcel.Columns.Count);
for (int i = 0; i < dtexcel.Columns.Count; i++)
     columnName[i] = dtexcel.Columns[i].ColumnName;

If the field is null but the column has items then its name will be "F{i}", where i is a number of column.

2 Comments

table[i] dtexcel.Columns[i].ColumnName; ?
equal sign was missed :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.