栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

Winform窗体程序实现Excel表格数据导入数据库

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Winform窗体程序实现Excel表格数据导入数据库

废话少说了,上代码。

首先我有一个Excel表格

红色部分为表头,也就是数据库的字段,蓝色为每个字段对应的数据。

注意事项:Excel后缀必须是xls格式,不能是xlsx格式

其次,明确要导入的目标数据库,我使用的是Sql server

public static string connString = ConfigurationManager.AppSettings["ConnectionString"];

配置文件内容: 



     
        
    
	
		
	

关于这个配置文件详细使用,请移步: https://blog.csdn.net/weixin_39237340/article/details/92561824

建立一个窗体,托入一个button按钮,双击进入Click事件

上代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 实现Excel表格导入数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static string connString = ConfigurationManager.AppSettings["ConnectionString"];//导入目标数据库
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                TransferData(fd.FileName, "Tables", connString); 
            }
        }
  
        public void TransferData(string excelFile, string sheetName, string connectionString)
        {
            DataSet ds = new DataSet();
            try
            {
                //获取全部数据     
                 string strConn = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties = Excel 8.0;";
               //string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';",excelFile);
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                string strExcel = "";
                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
                OleDbDataAdapter myCommand = null;
                // strExcel = string.Format("select * from [" + sheetName + "$]");//"["和"$"两个符号都不能省.
                strExcel = string.Format("select * from ["+ sheetName + "] ");
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                myCommand.Fill(ds, sheetName);

                //如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录     
                string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName);   //以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导入数据        
                //excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的
                using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
                {
                    bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
                    bcp.BatchSize = 100;//每次传输的行数        
                    bcp.NotifyAfter = 100;//进度提示的行数        
                    bcp.DestinationTableName = sheetName;//目标表        
                    bcp.WriteToServer(ds.Tables[0]);
                }
              //  MessageBox.Show("完成");
            }
            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.Update();
        }
    }
}   

  有个点需要注意的地方, 调用TransferData(xx,xx,xx)方法第二个参数传的Excel的表名,我的Excel文件命名是Tables,所以直接在里面写死了。可以自己动态获取Excel的名称。

 以上内容出自的地方不记得了,如有侵权,联系本人删除。

 最后数据库:自动生成的表名,列名根据需求,提前在Excel表格中,先定义好。后面就不用在数据库里面再更改了。

 

根据Excel工作表命名,自动生成数据库表名

 资源下载:https://download.csdn.net/download/weixin_39237340/15615425

 学废了就点个赞支持一下吧 ^_^

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985350.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号