在 Visual Studio 2010 中将 Excel 数据导入 DataGridView

Posted

技术标签:

【中文标题】在 Visual Studio 2010 中将 Excel 数据导入 DataGridView【英文标题】:Import Excel data to DataGridView in Visual Studio 2010 【发布时间】:2013-07-10 10:43:43 【问题描述】:

请使用以下代码帮助修复将数据从 Excel 文档导入到DataGridView 控件:

private void button5_Click(object sender, EventArgs e)

    Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
    Excel.Workbook workbook =app.Workbooks.Open(@"C:\Users\Admin\Desktop\Dropbox\Vandit's Folder\Internship\test.xlsx");
    Excel.Worksheet worksheet = workbook.ActiveSheet;

    rcount = worksheet.UsedRange.Rows.Count;

    int i = 0;

    for(;i<rcount;i++)
    
        dataGridView1.Rows[i].Cells["Column1"].Value = worksheet.Cells[i + 1, 1].Value;
        dataGridView1.Rows[i].Cells["Column2"].Value = worksheet.Cells[i + 1, 2].Value;
    

当我运行这段代码时,我总是得到一个异常提示

"Index was out of range. Must be non-negative and less than the size of the collection."
"Parameter name: index."

【问题讨论】:

看,rowcountdataGridView1 为 0。因此,当调用 dataGridView1.Rows[i].Cells["Column1"].Value 时,未找到 Rows[0] 并引发异常。代码在这里所做的是修改数据网格中单元格的现有值,这些值尚不存在。所以请不要修改插入数据到数据网格中。 【参考方案1】:

假设dataGridView1 有 2 列,

private void button5_Click(object sender, EventArgs e)

    Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
    Excel.Workbook workbook =app.Workbooks.Open(@"C:\Users\Admin\Desktop\Dropbox\Vandit's Folder\Internship\test.xlsx");
    Excel.Worksheet worksheet = workbook.ActiveSheet;

    rcount = worksheet.UsedRange.Rows.Count;

    int i = 0;        

    for(;i<rcount;i++)
    
        //dataGridView1.Rows[i].Cells["Column1"].Value = worksheet.Cells[i + 1, 1].Value;
        //dataGridView1.Rows[i].Cells["Column2"].Value = worksheet.Cells[i + 1, 2].Value;
        dataGridView1.Rows.Add(worksheet.Cells[i + 1, 1].Value, worksheet.Cells[i + 1, 2].Value);
    

假设dataGridView1 有 0 列,

private void button5_Click(object sender, EventArgs e)

    Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
    Excel.Workbook workbook =app.Workbooks.Open(@"C:\Users\Admin\Desktop\Dropbox\Vandit's Folder\Internship\test.xlsx");
    Excel.Worksheet worksheet = workbook.ActiveSheet;

    rcount = worksheet.UsedRange.Rows.Count;

    int i = 0;

    //Initializing Columns
    dataGridView1.ColumnCount = worksheet.UsedRange.Columns.Count;
    for(int x=0;x<dataGridView1.ColumnCount;x++)
    
            dataGridView1.Columns[x].Name = "Column "+x.ToString();
    

    for(;i<rcount;i++)
    
        //dataGridView1.Rows[i].Cells["Column1"].Value = worksheet.Cells[i + 1, 1].Value;
        //dataGridView1.Rows[i].Cells["Column2"].Value = worksheet.Cells[i + 1, 2].Value;
        dataGridView1.Rows.Add(worksheet.Cells[i + 1, 1].Value, worksheet.Cells[i + 1, 2].Value);
    

【讨论】:

我很高兴...谢谢它的工作,因为我忘了提到我手动编写了更改并且没有测试它们。 :)【参考方案2】:

你可以像下面这样添加行

for(int i=0;i<rcount;i++)

 dataGridView1.Rows.Add(orksheet.Cells[i + 1, 1].Value,  worksheet.Cells[i + 1, 2].Value);

您正在做的是设置gridview 现有行的值。如果gridview没有索引给出的行那么你会得到异常

但如果没有这些,您可以使用 Ado.net 并从 excel 中读取数据并将其绑定到 gridview。从KB article查看下面的示例代码

// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
    "Extended Properties=Excel 8.0;";

// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);

// Open connection with the database.
objConn.Open();

// The code to follow uses a SQL SELECT command to display the data from the worksheet.

// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);

// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;

// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();

// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");

// Bind data to DataGrid control.
DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();

// Clean up objects.
objConn.Close();

【讨论】:

【参考方案3】:

此错误意味着引发错误的索引在gridview中不存在或您的excel文件中缺少列。

datagridView 中的索引数必须等于您为 datagridview 发送的字段数。

【讨论】:

【参考方案4】:

试试下面的代码

 DialogResult dialogResult = MessageBox.Show("Sure", "Some  Title",MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)



    dt = dsSource.Tables[Index];

    dt.Reset();
    Excel.Workbook workbook;
    Excel.Worksheet NwSheet;
    Excel.Range ShtRange;
    Microsoft.Office.Interop.Excel.Application ExcelObj = new                 Microsoft.Office.Interop.Excel.Application();
    OpenFileDialog filedlgExcel = new OpenFileDialog();
    filedlgExcel.Title = "Select file";
    filedlgExcel.InitialDirectory = @"c:\";
    //filedlgExcel.FileName = textBox1.Text;
    filedlgExcel.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
    filedlgExcel.FilterIndex = 1;
    filedlgExcel.RestoreDirectory = true;
    if (filedlgExcel.ShowDialog() == DialogResult.OK)
    

        workbook = ExcelObj.Workbooks.Open(filedlgExcel.FileName, Missing.Value, Missing.Value,
             Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
             Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
        ShtRange = NwSheet.UsedRange;
        for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
        
            dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
        
        dt.AcceptChanges();
        string[] columnNames = new String[dt.Columns.Count];
        for (int i = 0; i < dt.Columns.Count; i++)
        
            columnNames[0] = dt.Columns[i].ColumnName;
        
        //string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();


        for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
        
            DataRow dr = dt.NewRow();
            for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
            
                if ((ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2 != null)
                
                    dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
                
            
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        
        workbook.Close(true, Missing.Value, Missing.Value);
        ExcelObj.Quit();

        dataGridView1.DataSource = dt;  

【讨论】:

以上是关于在 Visual Studio 2010 中将 Excel 数据导入 DataGridView的主要内容,如果未能解决你的问题,请参考以下文章

在 Visual Studio 2010 中将输出消息写入“输出窗口”的最简单方法?

在 Visual Studio 2010 负载测试用户包中将用户数升级到 250 或更多

如何在 Visual Studio 2010 Express 中将 cpp 编译为 dll

在Visual Studio 2010中将Native / C ++ DLL链接到托管C ++ / CLI包装器

无法在 Visual Studio 2015 中将 typedef 转换为 std::pair

如何在 Visual Studio 2010 中使用互斥锁