.net中将EXCEL表格导入导到sqlserver数据库中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source='C:/Users/Administrator/Desktop/全部企业代码证121.xls';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
            string mystring = "Provider =Microsoft.Jet.OLEDB.4.0 ; Data   Source   = C:/Users/Administrator/Desktop/全部企业代码证121.xls ;Extended   Properties=Excel   8.0";
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter myDa = new OleDbDataAdapter("select   *   from   [Sheet1$] ", cnnxls);
            DataSet myDs = new DataSet();
            myDa.Fill(myDs);

            if (myDs.Tables[0].Rows.Count > 0)
            {
                string strSql = " ";
                string CnnString = "Provider=SQLOLEDB;database=temp;server=(local);uid=sa;pwd=123";
                OleDbConnection conn = new OleDbConnection(CnnString);
                conn.Open();
                OleDbCommand myCmd = null;

                for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
                {
                    strSql = "insert   into   new(name,code)   values   ( ' ";
                    strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + " ',   ' ";
                    strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + " ') ";

                    try
                    {
                        myCmd = new OleDbCommand(strSql, conn);
                        myCmd.ExecuteNonQuery();
                    }
                    catch
                    {
                    }
                }
                conn.Close();
            }

        }
       
    }
}

posted on 2011-12-16 11:16  larryle  阅读(991)  评论(0)    收藏  举报