使用C#将Excel数据导入DataGridView

时间:2014-03-01 08:41:58

标签: c# excel datagridview

我想将Excel数据导入DataGridView控件,我已经拥有此代码:

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Open(file);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;

Range excelRange = worksheet.UsedRange;

int numberOfRows = excelRange.Rows.Count;
int numberOfCols = excelRange.Columns.Count;

for (int i = 0; i < numberOfRows; i++)
{
    for (int j = 0; j < numberOfCols; j++)
    {
dgvIM.Rows.Add(worksheet.Cells[i + 1, 1].Value, worksheet.Cells[i + 1, 2].Value);
    }
}

这会引发System.InvalidOperationException错误 并在更改为dgvIM.Rows.Add(worksheet.Cells[i, j].Value, worksheet.Cells[i, j].Value); - &gt;之后System.Runtime.InteropServices.COMException

1 个答案:

答案 0 :(得分:0)

试试这个

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
                if (fileExtention == ".xls" || fileExtention == ".xlsx")
                {
                    string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPath("~/ExcelSheet/" + fileName));
                   /*Read excel sheet*/
                    string excelSheetFilename = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/ExcelSheet/" + fileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    OleDbConnection objcon = new OleDbConnection(excelSheetFilename);
                    string queryForExcel = "Select * from [UserDetail$];";
                    OleDbDataAdapter objda = new OleDbDataAdapter(queryForExcel, objcon);
                    DataSet objds = new DataSet();
                    objda.Fill(objds);
                    if (objds.Tables[0].Rows.Count > 0)
                    {
                        GridView1.DataSource = objds.Tables[0];
                        GridView1.DataBind();
                    }
                }
                else
                {
                    lblMessage.Text = "Please upload excel sheet.";
                }
            }
        }
    }
}

首先,它上传excel文件,并在gridview中显示该数据。

有关详细信息,请参阅此Excel File Upload Or Import and Display In GridView Using C# In Asp.Net