当前位置:Gxlcms > 数据库问题 > 读取Excel的记录并导入SQL数据库

读取Excel的记录并导入SQL数据库

时间:2021-07-01 10:21:17 帮助过:22人阅读

System.Configuration; using System.Data; using System.Data.OleDb; using System.Data.SqlClient;

 

你可以写一个方法,是去读取Excel文档的方法,返回DataSet数据集:
技术分享

 

技术分享
private DataSet ImportExcelToDataSet(string virtualPath, string sqlQueryStatement)
    {
        string excelConnectionString = DB.ExcelConnectionString(Server.MapPath(virtualPath));
        OleDbConnection dc = new OleDbConnection(excelConnectionString);
        OleDbDataAdapter da = new OleDbDataAdapter(sqlQueryStatement, dc);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
Source Code


导入数据库,在数据库中,需要创建一个表来存储Excel导入来的数据:
技术分享


接下来,你可以使作SqlBulkCopy的方法进行复制数据库:

技术分享

 

技术分享
try
        {
            string cs = ConfigurationManager.ConnectionStrings["InsusSqlConnectionString"].ConnectionString;
            using (SqlConnection sqlConn = new SqlConnection(cs))
            {
                string sqlQueryStatement = "SELECT [Material],[Plnt],[Level],[Item],[Component],[Object description] FROM [Sheet1$]";
                string virtualPath = "~/App_Data/Book1.xlsx";

                DataSet ds = ImportExcelToDataSet(virtualPath, sqlQueryStatement);

                DataTable dt = ds.Tables[0];

                sqlConn.Open();
                using (SqlBulkCopy sqlbc = new SqlBulkCopy(sqlConn))
                {
                    sqlbc.DestinationTableName = "BOM";
                    sqlbc.ColumnMappings.Add("Material", "Material");
                    sqlbc.ColumnMappings.Add("Plnt", "Plnt");
                    sqlbc.ColumnMappings.Add("Level", "Level");
                    sqlbc.ColumnMappings.Add("Item", "Item");
                    sqlbc.ColumnMappings.Add("Component", "Component");
                    sqlbc.ColumnMappings.Add("Object description", "Object description");
                    sqlbc.WriteToServer(dt);
                    Response.Write("数据导入成功!");
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
Source Code


演示:
技术分享

 

读取Excel的记录并导入SQL数据库

标签:com   color   bom   创建   l数据库   cli   需要   add   splay   

人气教程排行