首页 > 代码库 > CSV导入SQLSERVER数据库

CSV导入SQLSERVER数据库

    /// <summary>    /// 通过文件流的方式来读取CSV文件    /// </summary>    /// <param name="files">文件名称</param>    /// <param name="HeadYes">第一行是否为列标题</param>    /// <param name="span">分隔符</param>    /// <returns></returns>    public DataTable ReadCsvFileToTable(bool HeadYes, char span)    {        //文件路径和文件名        string files = path + fileName;        DataTable dt = new DataTable();        StreamReader fileReader = new StreamReader(files, Encoding.Default);        try        {            //是否为第一行(如果HeadYes为TRUE,则第一行为标题行)            int lsi = 0;            //列之间的分隔符            char cv = span;            while (fileReader.EndOfStream == false)            {                string line = fileReader.ReadLine();                string[] y = line.Split(cv);                //第一行为标题行                if (HeadYes == true)                {                    //第一行                    if (lsi == 0)                    {                        for (int i = 0; i < y.Length; i++)                        {                            dt.Columns.Add(y[i].Trim().ToString());                        }                        lsi++;                    }                    //从第二列开始为数据列                    else                    {                        DataRow dr = dt.NewRow();                        for (int i = 0; i < y.Length; i++)                        {                            dr[i] = y[i].Trim();                        }                        dt.Rows.Add(dr);                    }                }                //第一行不为标题行                else                {                    if (lsi == 0)                    {                        for (int i = 0; i < y.Length; i++)                        {                            dt.Columns.Add("Col" + i.ToString());                        }                        lsi++;                    }                    DataRow dr = dt.NewRow();                    for (int i = 0; i < y.Length; i++)                    {                        dr[i] = y[i].Trim();                    }                    dt.Rows.Add(dr);                }            }        }        catch (Exception ex)        {            throw ex;        }        finally        {            fileReader.Close();            fileReader.Dispose();        }        return dt;    }
    private string conn = ConfigurationManager.ConnectionStrings["ConStr"].ToString();
/// <summary>
/// 将指定表的数据Copy至目标数据库 /// </summary> /// <param name="dt">数据表</param> /// <param name="outTime">超时时间</param> /// <returns></returns> public string CopyTableToSql(DataTable dt, int outTime, string tableName) { SqlBulkCopy sbc = new SqlBulkCopy(conn, SqlBulkCopyOptions.UseInternalTransaction); sbc.BulkCopyTimeout = outTime; sbc.NotifyAfter = dt.Rows.Count; try { sbc.DestinationTableName = tableName; sbc.WriteToServer(dt); return ""; } catch (Exception ex) { return ex.Message; } finally { sbc.Close(); } }