上载Excel工作表并将数据导入SQL Server数据库

Hem*_*som 12 c# asp.net-mvc sql-server-2008

我正在开发这个简单的应用程序来上传Excel文件(.xlsx)并将该Excel工作表中的数据导入.NET中的SQL Server Express数据库

我在浏览并选择要执行此操作的文件后单击导入按钮时使用以下代码.

protected void Button1_Click(object sender, EventArgs e)
{
        String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
        //file upload path
        string path = FileUpload1.PostedFile.FileName;
        //string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
        //Create connection string to Excel work book
        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
        //Create Connection to Excel work book
        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
        //Create OleDbCommand to fetch data from Excel
        OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
        //Give your Destination table name
        sqlBulk.DestinationTableName = "Excel_table";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();
    }
Run Code Online (Sandbox Code Playgroud)

但是当我使用时,代码不会运行

string path = FileUpload1.PostedFile.FileName;`
Run Code Online (Sandbox Code Playgroud)

乃至

string path="C:\ Users\ Hemant\Documents\example.xlsx";` 
Run Code Online (Sandbox Code Playgroud)

dReader无法采取的路径这种格式.

它只能采用以下格式的路径

string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
Run Code Online (Sandbox Code Playgroud)

即使用\\路径中的路径.我必须对路径进行硬编码,但我们必须浏览文件.

那么,任何人都可以建议一个解决方案来使用FileUpload1导入数据的路径吗?

das*_*ash 17

你正在处理一个HttpPostedFile; 这是"上传"到Web服务器的文件.你真的需要在某处保存该文件然后使用它,因为...

...在您的实例中,恰好是您在网络所在的同一台机器上托管您的网站,因此可以访问该路径.只要将站点部署到其他计算机,代码就无法运行.

将其分解为两个步骤:

1)将文件保存在某个地方 - 这很常见:

string saveFolder = @"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files

string filePath = Path.Combine(saveFolder, FileUpload1.FileName); 

FileUpload1.SaveAs(filePath);
Run Code Online (Sandbox Code Playgroud)

现在,您可以在本地获取文件,并且可以完成实际工作.

2)从文件中获取数据.您的代码应该按原样运行,但您可以这样简单地编写连接字符串:

string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
Run Code Online (Sandbox Code Playgroud)

然后,您可以考虑删除刚刚上传和导入的文件.

为了提供更具体的示例,我们可以将您的代码重构为两种方法:

    private void SaveFileToDatabase(string filePath)
    {
        String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";

        String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
        //Create Connection to Excel work book 
        using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
        {
            //Create OleDbCommand to fetch data from Excel 
            using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
            {
                excelConnection.Open();
                using (OleDbDataReader dReader = cmd.ExecuteReader())
                {
                    using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                    {
                        //Give your Destination table name 
                        sqlBulk.DestinationTableName = "Excel_table";
                        sqlBulk.WriteToServer(dReader);
                    }
                }
            }
        } 
    }


    private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
    {


        string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);

        fileUploadControl.SaveAs(filePath);

        return filePath;

    }
Run Code Online (Sandbox Code Playgroud)

你可以简单地打电话 SaveFileToDatabase(GetLocalFilePath(@"C:\temp\uploads", FileUpload1));

请考虑查看Excel连接字符串的其他扩展属性.它们有用!

您可能想要做的其他改进包括将Sql Database连接字符串放入config,并添加适当的异常处理.请考虑此示例仅供演示!