-1

我正在将 excel 文件读入 C#.NET 中的 dataGridView 中,但是它为第一行呈现列标题,如何消除呈现列标题以便所有行看起来都一样?

我有 openDialogBox1 和 button1 来打开这个对话框并选择 excel 文件:

private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {                
                Excel.Application excelApp = new Excel.Application();
                //excelApp.Visible = true;

                Excel.Workbook theWorkbook = excelApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5,
                                                                    "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
                                                                    0, true);
                Excel.Sheets sheets = theWorkbook.Worksheets;
                Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);

                /*
                for (int i = 1; i <= 3; i++)
                {
                    Excel.Range range = worksheet.get_Range("A"+i.ToString(), "B" + i.ToString());
                    dataGridView1.DataSource = rangeTable(range);                                        
                }
                 */
                Excel.Range range = worksheet.get_Range("A1", "B3");
                dataGridView1.DataSource = rangeTable(range);                                                                 
            }            
        }

        private DataTable rangeTable(Excel.Range range)
        {
            DataTable dataTable = new DataTable();
            int rowCnt = range.Rows.Count;
            int colCnt = range.Columns.Count;

            for (int i = 1; i <= rowCnt; i++)
            {
                DataRow newRow = dataTable.NewRow();
                for (int j = 1; j <= colCnt; j++)
                {
                    if (i == 1)
                    {
                        dataTable.Columns.Add(((Excel.Range)range.get_Item(i, j)).Value2.ToString(), typeof(string));
                    }
                    else
                    {
                        newRow[j - 1] = ((Excel.Range)range.get_Item(i, j)).Value2;
                    }
                }
                if (i > 1)
                {
                    dataTable.Rows.Add(newRow);
                }
            }
            return dataTable;
        }

谢谢

4

1 回答 1

0

设置RowHeadersVisible="false" 请参见此处:http: //msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowheadersvisible.aspx

于 2012-10-11T19:06:51.290 回答