将Excel, txt, cvs等文件导入SQL的方法汇总

EXCEL

1. 用SQLBulkCopy导入Excel, 有点类似ssis导入工具,可以匹配字段关系,方便日期,字符串等多种格式的导入

#region 用sqlBulkCopy导入,可以解决数据类型问题



        public static void sqlBulkCopyFromExcel(string excelFilePath, string oleSqlStr, string sqlConnStr, string DestinationTableName)

        {

////excelFilePath: 源文件excel的全路径;   oleSqlStr: Excel数据选取的SQL语句,'SELECT * FROM [Sheet1$]'

////sqlConnStr: server connection string;  DestinationTableName: 目标server表名





            //DateTime t1 = DateTime.Now;

            //string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";



      //可以处理Excel 2003和Excel 2007

            string excelConnectionString = @"Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFilePath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";



            using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))

            {



                excelConnection.Open();

                //Getting source data

                

                OleDbCommand command = new OleDbCommand(oleSqlStr, excelConnection);

                // Initialize SqlBulkCopy object



                using (OleDbDataReader dr = command.ExecuteReader())

                {

                    // Copy data to destination



                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnStr))

                    {

                        bulkCopy.DestinationTableName = DestinationTableName;

                        //加入只加入一個列的話,那么就會其他數據庫列都默認為空。

                        //bulkCopy.ColumnMappings.Add("Region", "region");

                        //bcp.BatchSize = 100;//每次传输的行数

                        //bcp.NotifyAfter = 100;//进度提示的行数

                        bulkCopy.BatchSize = 10000;

                        //bulkCopy.NotifyAfter = 10000;

                        bulkCopy.WriteToServer((IDataReader)dr);

                    }

                }

                //Closing connection

                excelConnection.Close();

            }



        }



        #endregion 
View Code
 
   
2. 运用Microsoft.Office.Interop.Excel命名空间的功能导入
    
        #region 导入EXCEL

        public static void ImportExcel(System.Windows.Forms.TextBox txtFilePath, string[] strExcelColumnNm, string lastRowColumn, bool IsHWinfo, string inserIntoPath)

        {



            //missing value

            System.Reflection.Missing missingValue = System.Reflection.Missing.Value;



            string filePath = txtFilePath.Text;



            //string Result = tbResult.Text;



            Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = null;

            Microsoft.Office.Interop.Excel._Workbook ExcelBook = null;

            try

            {



                //取得Excel Application对象

                ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

                //设定打开语言

                System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;

                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");



                //取得Template文件对象

                ExcelBook = ExcelApp.Workbooks.Open(filePath, missingValue,

                    missingValue, missingValue, missingValue, missingValue, missingValue, missingValue, missingValue,

                    missingValue, missingValue, missingValue, missingValue, missingValue, missingValue);

                Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelBook.Worksheets[1];



                //Sheet的最大数据行数

                int intLastRow = 0;



                //取得此Sheet的最大数据行数

                intLastRow = ExcelSheet.get_Range(lastRowColumn + ExcelSheet.Rows.Count, Type.Missing).get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;





                //int j = 0;



                //Excel Range对象

                Microsoft.Office.Interop.Excel.Range rng;



                //循环Sheet中的每条数据

                for (int i = 2; i <= intLastRow; i++)

                {

                    //定义插入字符串

                    string strData = string.Empty;



                    //数组下标

                    int intArrayIdx = 0;



                    //得到ASSET_TAG自动所在单元格

                    for (int j = 0; j < strExcelColumnNm.Length; j++)

                    {

                        rng = ExcelSheet.get_Range(strExcelColumnNm[intArrayIdx++] + i.ToString(), Type.Missing);

                        strData += "'" + rng.Value2.ToString().Trim() + "',";



                    }

                    strData = strData.Substring(0, strData.Length - 1);

                    //调用方法将数据插入到数据库中  

                    InsertInfo(inserIntoPath, strData);





                }

            }

            catch

            {

                return;



            }

            finally

            {

                CloseExcel(ExcelApp, ExcelBook);

            }

        }

        public static void InsertInfo(string insertIntoPath, string data)

        {

            //定义链接字符串

            String strConn = ConfigurationSettings.AppSettings["connString"];



            using (SqlConnection con = new SqlConnection())//创建链接

            {

                con.ConnectionString = strConn;

                //打开链接

                con.Open();

                //创建

                SqlCommand cmd = new SqlCommand();

                cmd.Connection = con;



                string sqlCmd = "INSERT INTO " + insertIntoPath + "VALUES(" + data + ")";





                cmd.CommandText = sqlCmd;



                cmd.ExecuteNonQuery();

            }

        }

        # endregion

        #region 关闭EXCEL

        public static void CloseExcel(Microsoft.Office.Interop.Excel.ApplicationClass ExcelApplication, Microsoft.Office.Interop.Excel._Workbook ExcelWorkbook)

        {

            ExcelWorkbook.Close(false, Type.Missing, Type.Missing);

            ExcelApplication.Quit();

            //kill all excel course

            KeyMyExcelProcess.Kill(ExcelApplication);

        }

        public class KeyMyExcelProcess

        {

            [DllImport("User32.dll", CharSet = CharSet.Auto)]

            public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

            public static void Kill(Microsoft.Office.Interop.Excel.Application excel)

            {

                try

                {

                    IntPtr t = new IntPtr(excel.Hwnd);   //得到这个句柄,具体作用是得到这块内存入口 



                    int k = 0;

                    GetWindowThreadProcessId(t, out k);   //得到本进程唯一标志k

                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);   //得到对进程k的引用



                    p.Kill();     //关闭进程k

                }

                catch (Exception ex)

                {



                    throw ex;

                }

            }

        }

        #endregion
View Code

 

 3. 用NPOI,导出Excel功能实现用NPOI最便捷,但是NPOI对Excel2003以上版本支持有限,导入功能实现不足

TXT, CSV
1.T-SQL的“BULK INSERT”语句可以直接将txt, csv文件导入SQL SERVER
Sql代码 

BULK INSERT [ [ 'database_name'.][ 'owner' ].]{ 'table_name' FROM 'data_file' }       

WITH  (   

        [ BATCHSIZE [ = batch_size ] ],       

        [ CHECK_CONSTRAINTS ],           

        [ CODEPAGE [ = 'ACP' | 'OEM' | 'RAW' | 'code_page' ] ],   

        [ DATAFILETYPE [ = 'char' | 'native'| 'widechar' | 'widenative' ] ],               

        [ FIELDTERMINATOR [ = 'field_terminator' ] ],   

        [ FIRSTROW [ = first_row ] ],   

        [ FIRE_TRIGGERS ],   

        [ FORMATFILE = 'format_file_path' ],   

        [ KEEPIDENTITY ],   

        [ KEEPNULLS ],   

        [ KILOBYTES_PER_BATCH [ = kilobytes_per_batch ] ],      

        [ LASTROW [ = last_row ] ],   

        [ MAXERRORS [ = max_errors ] ],   

        [ ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) ],     

        [ ROWS_PER_BATCH [ = rows_per_batch ] ],   

        [ ROWTERMINATOR [ = 'row_terminator' ] ],             

        [ TABLOCK ],   

)  
View Code
 
   
SQLHelper.ExecuteNonQuery("BULK INSERT SCCM FROM '" + 文件全路径 + "'WITH (FIRSTROW=2,FIELDTERMINATOR ='\t',ROWTERMINATOR='\n')");
 
  

 待续...

你可能感兴趣的:(Excel)