ASP上传Exel文件到Web错误:Microsoft Office Access数据库引擎无法打开或写入该文件

时间:2016-08-09 02:16:57

标签: c# asp.net excel

在我的应用程序中,我尝试将Excel数据文件从本地计算机上传到SQL数据库到web somee.com服务器。我在当地测试了一切正常。在服务器计算机中部署应用程序并尝试运行后,我收到类似&#34的错误; Microsoft Office Access数据库引擎无法打开或写入文件''。它已由另一个用户专门打开,或者您需要获得查看和写入其数据的权限“。我尝试在我的excel文件所在的文件夹UploadExcel上授予NETWORK SERVICE帐户修改权限;不幸的是,它没有用。

ASPX.CS:

    static string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    public static string path = @"C:\UploadExcel\Sheet1.xls";
    public static string connStexcelConnectionStringr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

    protected void Page_Load(object sender, EventArgs e)
    {
        txtTime.Attributes.Add("readonly", "readonly");                     
        string department_login = "";                                       
        bool check_login = authenticate.isAuthenticated();           

        if (check_login == false)
        {
            Response.Redirect("SPC_HP_trangdangnhap.aspx");
        }

        if (!this.IsPostBack)
        {
            string username = Session["UserId"].ToString();                 
            department_login = authenticate.authenticateLogin(username);   

            if (!department_login.Equals("Kế toán"))
            {
                Response.Redirect("SPC_HP_trangdangnhap.aspx");
            }
            else
            {
                BindGrid();
            }
        }
    }

    private void BindGrid()
    {
        DateTime Day_Today = DateTime.Today;                  
        string today = Day_Today.ToString("yyyy-MM-dd");        
        String strCmd = "";

        DataSet ds = new DataSet();

        strCmd += "SELECT ProductSPCCode, MaterialNameDB, ProductUnitStock, REPLACE(CONVERT(varchar,CONVERT(Money, ProductTypeA),1),'.00','') AS ProductTypeA, REPLACE(CONVERT(varchar,CONVERT(Money, ProductTypeB),1),'.00','') AS ProductTypeB ";
        strCmd += "FROM ProductStockTemp ";
        strCmd += "WHERE ProductStockTime = '"+ today + "'";

        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(strCmd, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Close();

            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                grdProductStock.DataSource = ds;
                grdProductStock.DataBind();
                int column_count = grdProductStock.Rows[0].Cells.Count;
                grdProductStock.Rows[0].Cells.Clear();
                grdProductStock.Rows[0].Cells.Add(new TableCell());
                grdProductStock.Rows[0].Cells[0].ColumnSpan = column_count;
                grdProductStock.Rows[0].Cells[0].Text = "Chưa có tồn kho!";
            }
            else
            {
                grdProductStock.DataSource = ds;
                grdProductStock.DataBind();
            }
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", fupExcel.PostedFile.FileName);
        string timeJ = txtTime.Text;
        string time = DateTime.ParseExact(timeJ, "dd'/'MM'/'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'-'MM'-'dd");
        DateTime.ParseExact(time, "yyyy-MM-dd", CultureInfo.InvariantCulture);
        DateTime Day_Today = DateTime.Today;
        string today = Day_Today.ToString("yyyy-MM-dd");
        string file_Path = fupExcel.PostedFile.FileName;        
        string file_name = Path.GetFileName(file_Path);        
        string ext = Path.GetExtension(file_name);              
        string type = String.Empty;                             

        if (!fupExcel.HasFile)
        {
            Response.Write("<script language='javascript'>alert('Xin chọn file Excel!!!')</script>");
            return;
        }
        else
            if (fupExcel.HasFile)
            {
                switch (ext)    
                {
                    case ".xls":
                        type = "application/vnd.ms-excel";
                        break;

                    /*case ".xlsx":
                        type = "application/vnd.ms-excel";
                        break;*/
                }

                if (type != String.Empty)
                {
                    try
                    {
                        using (SqlConnection con = new SqlConnection(constr))
                        {
                            using (SqlCommand cmd_delete = new SqlCommand("DELETE FROM ProductStockTemp WHERE ProductStockTime = '"+ time +"'"))
                            {
                                cmd_delete.Connection = con;
                                con.Open();
                                cmd_delete.ExecuteNonQuery();
                            }
                            con.Close();
                            con.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    using (OleDbConnection connection = new OleDbConnection(connStexcelConnectionStringr))
                    {
                        OleDbCommand command = new OleDbCommand(("Select *,'" + time + "' as [productTime] FROM [Sheet1$]"), connection);
                        connection.Open();
                        using (DbDataReader dr = command.ExecuteReader())
                        {
                            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(constr))
                            {
                                bulkCopy.DestinationTableName = "ProductStockTemp";

                                bulkCopy.ColumnMappings.Add("productTime", "ProductStockTime");
                                bulkCopy.ColumnMappings.Add("MÃ HÀNG", "ProductSPCCode");
                                bulkCopy.ColumnMappings.Add("TÊN HÀNG", "MaterialNameDB");
                                bulkCopy.ColumnMappings.Add("ĐVT", "ProductUnitStock");
                                bulkCopy.ColumnMappings.Add("LOẠI A", "ProductTypeA");
                                bulkCopy.ColumnMappings.Add("LOẠI B", "ProductTypeB");

                                try
                                {
                                    bulkCopy.WriteToServer(dr);
                                    Response.Write("<script language='javascript'>alert('Dữ liệu tồn kho Excel đã nhập vảo CSDL thành công!!!')</script>");
                                    BindGrid();
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                                finally
                                {
                                    dr.Close();
                                }
                            }
                        }
                    }
                }
                else
                {
                    Response.Write("<script language='javascript'>alert('Xin chọn file Excel có phần mở rộng .xls!!!')</script>");
                    return;
                }
            }
    }

    /* Method to exit */
    protected void imgExit_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("KT_trangchu.aspx");
    }
}

}

0 个答案:

没有答案