【问题标题】:reading data from excel file to gridView using asp.net使用asp.net从excel文件读取数据到gridView
【发布时间】:2014-03-11 07:06:30
【问题描述】:

美好的一天,我从 excel 文件中读取数据并将其显示给 gridview。但错误提示“Microsoft Jet 数据库引擎无法打开文件''。它已被其他用户以独占方式打开,或者您需要权限才能查看其数据。”

我做了什么:

  1. 为 IUSR、NETWORK_SERVICE、NETWORK、EVERYONE、USERS 和 ADMIN 授予对文件夹的完全访问权限

提前谢谢你。

String filePath = txtBbSource.Text;
    String sheetName = txtSheetName.Text;

    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
    OleDbConnection con = new OleDbConnection(constr);
    OleDbDataAdapter sda = new OleDbDataAdapter("Select * from [" + sheetName + "$]", con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gridBalances.DataSource = dt;  

【问题讨论】:

  • 我一直无法通过 OLEDB 访问 Excel。如果您正在处理较新的 .xlsx 格式,请查看 epplus.codeplex.com 作为替代方案。
  • 这可能与权限无关。任一文件已被其他用户、进程或您的代码使用。
  • @EricJ。我可能会在这周尝试 epplus.codeplex :)
  • @Serv 这是我的代码先生 serv。我很确定我关闭了excel。 =)
  • 您是否在使用程序阅读时保持打开的 Excel 文件?

标签: c# asp.net oledb


【解决方案1】:
private void FillGrid(string FilePath, string Extension)
{

        string conStr = "";
        DataTable dt = new DataTable();

        /*Add below Commented in Webconfig*/
         /*   <add name ="Excel03ConString"
     connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
                     Extended Properties='Excel 8.0;HDR={1}'"/>
          <!--connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
                     Extended Properties='Excel 8.0;HDR={1}'"/>-->
<add name ="Excel07ConString"
     connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
                     Extended Properties='Excel 8.0;HDR={1}'"/>
          * */
        switch (Extension)
        {
            case ".xls": //Excel 97-03
                conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07
                conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
        }
        conStr = String.Format(conStr, FilePath, "Yes");
        OleDbConnection connExcel = new OleDbConnection(conStr);
        OleDbCommand cmdExcel = new OleDbCommand();
        OleDbDataAdapter oda = new OleDbDataAdapter();

        cmdExcel.Connection = connExcel;
        try
        {
            int m = 1;
            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;

            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();

            //Read Data from First Sheet
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
            //oda.SelectCommand = cmdExcel;
            //oda.Fill(dt);
            // connExcel.Close();
            DataTable myColumns = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SheetName, null });

            foreach (DataRow dtRow in myColumns.Rows)
            {
                if (dtRow["COLUMN_NAME"].ToString() == "Sr No" && dtRow["ORDINAL_POSITION"].ToString() == "1")
                {
                    m++;
                }
                else if (dtRow["COLUMN_NAME"].ToString() == "Task Name" && dtRow["ORDINAL_POSITION"].ToString() == "2")
                {
                    m++;
                }
            }
            /*column count in excel*/
            if (m < 2)
            {
                lblErrMsg.Visible = true;
                lblErrMsg.Text = "Selected file is not in required template format.";
                return;
            }
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);
            connExcel.Close();
        }
        catch (Exception ex)
        {
            lblErrMsg.Visible = true;
            lblErrMsg.Text = "Selected file is not in required template format.";
            return;
        }

        DataTable dt_grd1 = new DataTable();
        DataRow drnewrow = null;


            //upload_plan = 1;
            foreach (DataRow dtRow in dt.Rows)
            {

                if (dtRow["Sr No"].ToString() == "" && dtRow["Task Name"].ToString() != "")
                {
                            dt_grd1.Columns.Add(new DataColumn("ID", typeof(string)));
                            dt_grd1.Columns.Add(new DataColumn("TASK_NAME", typeof(string)));    
                }

                    try
                    {
                        drnewrow = dt_grd1.NewRow();
                        drnewrow["ID"] = "";
                        drnewrow["TASK_NAME"] = dtRow["Task Name"].ToString();

                        dt_grd1.Rows.Add(drnewrow);

                    }
                    catch (Exception ex)
                    {
                        //lblError.Visible = true;
                        ////lblError.Text = ex.Message;// "Authentication failed. Please try later.";
                        //lblError.Text = DataInteraction.Constants.EXCEPTION;
                    }
                }

            /*Using Linq Find same TASK_NAME present in Excel*/
            if (dt_grd1.Rows.Count >= 1)
            {

                var Taskresult = from c in dt_grd1.AsEnumerable()
                                 group c by new
                                 {

                                     TaskName2 = c.Field<dynamic>("TASK_NAME"),


                                 } into g
                                 where g.Count() > 1
                                 select new
                                 {
                                     g.Key.TaskName2,

                                     //  g.Key.Pin,
                                     Noofrec = g.Count()
                                 };

                if (Taskresult.ToList().Count > 0)
                {
                    lblErrMsg.Visible = true;
                    div_err_log.Visible = false;
                    lblErrMsg.Text = "Task with same Name not allowed.";
                    return;
                }
            }
            grdTaskDataCat1.DataSource = dt_grd1;
            grdTaskDataCat1.DataBind();

            /*End 13th Jan'17*/
            lblErrMsg.Visible = true;
            lblErrMsg.Text = "Please confirm the details uploaded and press save to complete the upload of Bid plan.";
            return;


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多