在 Visual Studio 2010 中将 Excel 数据导入到 DataGridView [英] Import Excel data to DataGridView in Visual Studio 2010

查看:44
本文介绍了在 Visual Studio 2010 中将 Excel 数据导入到 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please help to fix importing data from Excel document to DataGridView control with following code:

private void button5_Click(object sender, EventArgs e)
{
    Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
    Excel.Workbook workbook =app.Workbooks.Open(@"C:UsersAdminDesktopDropboxVandit's FolderInternship	est.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;
    }
}

当我运行这段代码时,我总是收到一个异常说

when i run this code, I always get an exception saying

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

推荐答案

假设 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:UsersAdminDesktopDropboxVandit's FolderInternship	est.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:UsersAdminDesktopDropboxVandit's FolderInternship	est.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);
    }
}

这篇关于在 Visual Studio 2010 中将 Excel 数据导入到 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆