简体   繁体   English

C#-如何将标题从Excel转换为datagridview?

[英]C# - How to get the header from excel into datagridview?

I have the code below to import value from excel to datagridview. 我有下面的代码将值从excel导入到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(); 我曾尝试使用类似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;
    }  
 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. 此代码可以帮助您检查表中的所有记录。

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. 如果该字段为空,但该列中有项目,则其名称将为“ F {i}”,其中i是列数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM