首页 > 解决方案 > 如果excel文件在IIS express文件夹中,则只需将其导入数据库

问题描述

好吧,我正在做一个将数据从excel文件导入数据库(sql server)的程序。如果我将 excel 文件保存在 IIS express 文件夹中,程序运行良好,但如果我放入文档文件夹或类似文件夹,它会给我一个错误:

这是代码:

protected void Upload_Click(object sender, EventArgs e)
    {
        string filepath = FileUpload1.PostedFile.FileName;
        string filename = Path.GetFileName(filepath);
        string ext = Path.GetExtension(filename);
        String strConnection = @"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";

        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

        OleDbCommand cmd = new OleDbCommand("Select [Name],[City],[Age] from [Sheet1$]", excelConnection);
        excelConnection.Open();

        //cmd.ExecuteNonQuery();


       // DataSet ds = new DataSet();
       // SqlDataAdapter da = new SqlDataAdapter("Select [Name],[City],[Age] from [sheet1$]", strConnection);

        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);

        sqlBulk.DestinationTableName = "Test";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();
    }

标签: c#htmlasp.netweb

解决方案


尝试

   string filepath = Server.MapPath(FileUpload1.FileName);

推荐阅读