WinForm导入Excel,亲测可用(转载)

方法一(亲测可用)

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;  
     
namespace ExcelToSQL  
{  
    public partial class Form2 : Form  
    {  
        public Form2()  
        {  
            InitializeComponent();  
        }  
     
        DataTable dt = new DataTable();  
        string connString = "server = (local); uid = sa; pwd = sa; database = db_test";  
        SqlConnection conn;  
     
        private void button1_Click(object sender, EventArgs e)  
        {  
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();  
            if (fd.ShowDialog() == DialogResult.OK)  
            {  
                string fileName = fd.FileName;  
                bind(fileName);  
            }  
        }  
        private void bind(string fileName)  
        {  
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +  
                     "Data Source=" + fileName + ";" +  
                     "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";  
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT *  FROM [student$]", strConn);  
            DataSet ds = new DataSet();  
            try 
            {  
                da.Fill(ds);  
                dt = ds.Tables[0];  
                this.dataGridView1.DataSource = dt;  
            }  
            catch (Exception err)  
            {  
                MessageBox.Show("操作失败!" + err.ToString());  
            }  
        }  
     
        //将Datagridview1的记录插入到数据库    
        private void button2_Click(object sender, EventArgs e)  
        {  
            conn = new SqlConnection(connString);  
            conn.Open();  
            if (dataGridView1.Rows.Count > 0)  
            {  
                DataRow dr = null;  
                for (int i = 0; i < dt.Rows.Count; i++)  
                {  
                    dr = dt.Rows[i];  
                    insertToSql(dr);  
                }  
                conn.Close();  
                MessageBox.Show("导入成功!");  
            }  
            else 
            {  
                MessageBox.Show("没有数据!");  
            }  
        }  
        private void insertToSql(DataRow dr)  
        {  
            //excel表中的列名和数据库中的列名一定要对应  
            string name = dr["StudentName"].ToString();  
            string sex = dr["Sex"].ToString();  
            string no = dr["StudentIDNO"].ToString();  
            string major = dr["Major"].ToString();  
            string sql = "insert into student values('" + name + "','" + sex + "','" + no + "','" + major +"')";           
            SqlCommand cmd = new SqlCommand(sql, conn);             
            cmd.ExecuteNonQuery();  
        }  
    }  
}

方法二(未测试,应该也可以)

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;    
        
namespace ExcelToSQL    
{    
    public partial class Form1 : Form    
    {    
        public Form1()    
        {    
            InitializeComponent();    
        }    
        
        private void button1_Click(object sender, EventArgs e)    
        {    
            //测试,将excel中的student导入到sqlserver的db_test中,如果sql中的数据表不存在则创建        
            string connString = "server = (local); uid = sa; pwd = sa; database = db_test";    
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();       
            if (fd.ShowDialog() == DialogResult.OK)       
            {    
                TransferData(fd.FileName, "student", 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;";       
               OleDbConnection conn = new OleDbConnection(strConn);    
               conn.Open();    
               string strExcel = "";    
               OleDbDataAdapter myCommand = null;       
               strExcel = string.Format("select * from [{0}$]", 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]);    
               }       
            }       
            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();       
        }      
    }       
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForm导入Excel,可以借助CSDN上提供的相关教程和代码示例。导入Excel的一种常见方法是使用Microsoft.Office.Interop.Excel库。下面是大致的步骤: 1. 确保你的WinForm项目中已引用了Microsoft.Office.Interop.Excel库。 2. 在WinForm中添加一个按钮或其他控件,用于触发导入Excel的操作。 3. 在按钮的Click事件处理程序中编写代码。 4. 在事件处理程序中,首先创建一个Excel应用程序对象和一个工作簿对象。 5. 使用工作簿对象的Open方法打开Excel文件,指定文件的路径。 6. 使用工作簿对象的Worksheets属性来获取Excel文件中的工作表。 7. 通过遍历工作表集合,找到需要导入的工作表。 8. 使用工作表对象的Range属性,指定要导入的范围,例如"A1:D10"。 9. 使用Range对象的Value属性获取指定范围单元格的值,并将其存储到一个二维数组中。 10. 关闭工作簿和Excel应用程序对象,释放资源。 11. 可以根据需要对数组中的数据进行处理,并将其显示在WinForm的DataGridView等控件中。 需要注意的是,使用Microsoft.Office.Interop.Excel库需要安装相应的Office软件,且可能影响到部署和兼容性。如果不依赖于Office软件,可以考虑使用EPPlus、NPOI等第三方库来导入Excel,相关的示例代码也可以在CSDN上找到。 总之,导入Excel涉及到读取Excel文件、获取工作表、读取单元格的值等操作,通过参考CSDN上的教程和代码示例,可以较为容易地实现在WinForm导入Excel的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值