【问题标题】:Unable to Import Excel to Grid无法将 Excel 导入网格
【发布时间】:2014-02-06 10:29:47
【问题描述】:

我有一个带有导出到 Excel 和导入 Excel 的网格视图。但是,我可以成功地从 gridview 导出数据,当我尝试导入同一个 excel 时,我无法将该 excel 导入到网格中。但是当我更改 excel 文件名并导入时,它工作正常。

谁能告诉我为什么会这样?下面是我将 excel 导入网格的代码。

protected void btnImport_Click(object sender, EventArgs e)
{
    string sexcelconnectionstring = "";
    string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
    string path = FileUploadExcel.PostedFile.FileName;
    string query = "";
    Label1.Text = "";
    GridView2.Visible = false;

    if (strFileType != String.Empty)
    {
        //Connection String to Excel Workbook
        if (strFileType.Trim() == ".xls")
        {
            sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
        }
        else if (strFileType.Trim() == ".xlsx")
        {
            sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }

        OleDbConnection conn = new OleDbConnection(sexcelconnectionstring);
        if (conn.State == ConnectionState.Closed)
            conn.Open();

        System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        string sheetname = dt.Rows[0]["Table_Name"].ToString();

        try
        {
            query = "SELECT [Size],[Order],[Ratio] FROM [" + sheetname + "]";
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (objDA.IsValidExcelColumns(ds, GridView2, strSqlTable))
            {
                string sclearsql = "delete from " + strSqlTable;
                SqlConnection sqlconn = new SqlConnection(strConnectionString);
                SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
                sqlconn.Open();
                sqlcmd.ExecuteNonQuery();
                sqlconn.Close();

                //series of commands to bulk copy data from the excel file into our sql table
                OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
                oledbconn.Open();
                OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
                OleDbDataReader dReader;
                dReader = oledbcmd.ExecuteReader();
                SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnectionString);
                sqlBulk.DestinationTableName = strSqlTable;
                sqlBulk.WriteToServer(dReader);
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Data has been saved successfully.')", true);
            }

            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please validate the excel data.')", true);
            }
        }

        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded due to invalid column names.Please check: " + ex.Message;
        }

        conn.Close();
        conn.Dispose();
        objDA.BindGrid(GridView1, "select * from " + strSqlTable);
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
    }
}

这里是导出到excel的代码。

protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    string strQuery = "select * from " + strSqlTable;
    SqlCommand cmd = new SqlCommand(strQuery);
    System.Data.DataTable dt = GetData(cmd);

    //Create a dummy GridView
    GridView GridView1 = new GridView();
    GridView1.AllowPaging = false;
    GridView1.DataSource = dt;
    GridView1.DataBind();
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=MyExcelData.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        //Apply text style to each Row
        GridView1.Rows[i].Attributes.Add("class", "textmode");
    }
    GridView1.RenderControl(hw);

    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

【问题讨论】:

  • 错误发生在哪一行,错误是什么?
  • 发生在这一行 conn.Open();在 sexcel 连接字符串的正下方。错误:用户代码未处理 OleDbException。外部表不是预期的格式。
  • 作为一个建议:如果您不必加载旧的 xls 文件,您可以安全地使用像 epplus 这样的库来加载文件。它速度更快,更可靠。
  • 可能我必须加载 x​​ls 文件。

标签: c# asp.net .net gridview


【解决方案1】:

能否请您指定如何将数据导出到 Excel。您是否使用 office INTEROP 服务来导出数据?如果是这样,请使用垃圾收集器处理 excel 应用程序对象。然后尝试从excel导入数据。

我认为原因是当您将数据导出到 excel 文件时,在任务管理器中创建了一个新的 excel.exe。数据导出后,如果你没有关闭 excel 应用程序。对象,它仍然会在内存中。因此,当您尝试将相同的 excel 导入网格时,它会引发异常,因为该文件已在使用中且未处置。

using Marshal = System.Runtime.InteropServices.Marshal; To close excel application - excel.quit(); To dispose excel object - Marshal.ReleaseComObject(excel);

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    相关资源
    最近更新 更多