基本信息
源码名称:直接将Excel文件批量导入到自定义表
源码大小:0.06M
文件格式:.rar
开发语言:C#
更新时间:2021-10-05
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;

namespace FrmMain
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        OpenFileDialog dialog = new OpenFileDialog();
        private void button1_Click(object sender, EventArgs e)
        {
            if (TableName.Text == "")
            {
                MessageBox.Show("请选择要表名", "提示");
                TableName.Focus();
                return;
            }
            if (textBox2.Text=="")
            {
                MessageBox.Show("请选择要导入的文件", "提示");
                textBox2.Focus();
                return;
            }
            string table = TableName.Text.Trim();
            string connString = "server=localhost;uid=sa;pwd=123;database=TSHIS_PATIENT";
            string url = textBox2.Text.Trim();
            TransferData(url, table, connString);
 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //try
            //{
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                ofd.Title = "打开文件夹";
                string b = "";
                ofd.InitialDirectory = "c:\\";
                ofd.FilterIndex = 1;
                if (ofd.ShowDialog() == DialogResult.OK)  //如果点击的是打开文件
                {
                    this.textBox2.Text = ofd.FileName;  //获取全路径文件名
                    b = this.textBox2.Text;

                }
                //string tablename = gete(b);
                //string TSql = "SELECT*FROM[" tablename "]";
                //DataTable table = etds(b, TSql).Tables[0];
                //SqlBulkCopyInsert(sqlConnStr, tablename, table);
                //dataGridView1.DataSource = table;
                //将DataSet类对象table中存储的excel中的值放入
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
            //dialog.Filter = "所有文件(*.xls)|*.xls";
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    this.textBox2.Text = dialog.FileName;
            //}
        }
        /// <summary>
        /// 获得表名
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string gete(string path)
        {
            string tablename = null;
            if (File.Exists(path))
            {
                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                    path ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"))
                {
                    conn.Open();
                    tablename = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
                }
            }
            return tablename;
        }
        /// <summary>
        /// 使用OleDbDataAdapter对象mycommand将查询结果填充到DataTable对象ds中
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="tsql"></param>
        /// <returns></returns>
        public static DataSet etds(string filename, string tsql)
        {
            DataSet ds;
            string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                filename ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
            OleDbConnection myConn = new OleDbConnection(strcon);
            string strcom = tsql;
            myConn.Open();
            OleDbDataAdapter mycommand = new OleDbDataAdapter(strcom, myConn);
            ds = new DataSet();
            mycommand.Fill(ds);
            //使用OleDbDataAdapter对象mycommand将查询结果填充到DataTable对象ds中
            myConn.Close();
            return ds;
        }
        public void TransferData(string excelFile, string sheetName, string connectionString)
        {
            DataSet ds = new DataSet();
            try
            {
                //获取全部数据
                string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" "data source=" excelFile ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
                //string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" "Data Source=" excelFile ";" "Extended Properties='Excel 12.0;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                //包含excel中表名的字符串数组
                string[] strTableNames = new string[dtSheetName.Rows.Count];
                for (int k = 0; k < dtSheetName.Rows.Count; k )
                {
                    strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
                }
                strExcel = string.Format("select * from  [" strTableNames[0] "]", sheetName);
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                myCommand.Fill(ds, sheetName);
                //如果目标表不存在则创建
                string strSql = string.Format("if object_id('{0}') is null create table {0}(", sheetName);
                foreach (System.Data.DataColumn c in ds.Tables[0].Columns)
                {
                    strSql = string.Format("[{0}] varchar(255),", c.ColumnName);
                }
                strSql = strSql.Trim(',') ")";

                using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))
                {
                    sqlconn.Open();
                    System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();
                    command.CommandText = strSql;
                    command.ExecuteNonQuery();
                    sqlconn.Close();
                }
                //用bcp导入数据
                using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
                {
                    bcp.SqlRowsCopied = new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
                    bcp.BatchSize = 1000;//每次传输的行数
                    bcp.NotifyAfter = 1;//进度提示的行数
                    bcp.DestinationTableName = sheetName;//目标表
                    bcp.WriteToServer(ds.Tables[0]);
                    string tablename = TableName.Text.Trim();
                    MessageBox.Show("表 [" tablename "]导入成功", "提示"); 
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
        //进度显示
        void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
        {
            //this.Text = e.RowsCopied.ToString();
            this.textBox1.Text = e.RowsCopied.ToString();
            this.Update();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}