首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Excel将SQL大容量复制到SQL Server,但修改了数据

问使用Excel将SQL大容量复制到SQL Server,但修改了数据
EN

Stack Overflow用户
提问于 2012-01-12 02:33:46
回答 2查看 1.6K关注 0票数 0

我正在研读SQLBulkCopy,我想用它把Excel文档中的数千行导入到SQL Server中。我一直在读那些不修改数据就直接做的文章。在执行SQLBulkCopy之前,我需要对Excel文档中的数据进行一些修改和验证。有可能做到这一点吗?我假设我可以从重载中修改数据并创建一个大型DataTable,然后使用WriteToServer导入该DataTable。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-12 02:36:58

您可能需要一个DataReader或DataSet,以便在导入之前迭代以进行验证/修改。

此实用程序可能会帮助您- http://exceldatareader.codeplex.com/

票数 1
EN

Stack Overflow用户

发布于 2015-03-10 20:24:32

这对我来说很好:

代码语言:javascript
复制
    public ActionResult Create(HttpPostedFileBase file)
    {
        string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

        //file upload path
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);

        //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
        excelConnection.Open();
        DataTable dt = new DataTable();

        dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (dt == null)
        {
            return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int t = 0;
        //excel data saves in temp file here.
        foreach (DataRow row in dt.Rows)
        {
            excelSheets[t] = row["TABLE_NAME"].ToString();
            t++;
        }

        OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);

        string query = string.Format("SELECT * FROM [{0}]", excelSheets[0]);

        OleDbCommand cmd = new OleDbCommand(query, excelConnection);
        //excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
        //Give your Destination table name
        sqlBulk.DestinationTableName = "[FSM].[DFS_Akustik]";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();

        ViewBag.view_dfs_akustik = dbman.View_DFS_Akustik.ToList();
        return View();
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8824688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档