WinForm Excel导入

 

 主要代码如下:

定义一个DataSet   存放Excel读取的数据

 /// <summary>
        /// Excel 表中读取的数据
        /// </summary>
        public DataSet ExcelData
        {
            get;
            set;
        }

获取Excel模板:

  //获取Excel模板
        private void sbtnGet_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            //sfd.Filter = "Excel|*xls";
            sfd.Filter = "(*.xls,*.xlsx)|*.xls;*.xlsx"; 
            sfd.FileName = "学生信息"+DateTime.Now.ToString("yyyy-MM-dd")+".xls";
            if (sfd.ShowDialog(this) == DialogResult.OK) {
                string fileName = Application.StartupPath + "\\config\\学生信息模板.xls";
                if (File.Exists(fileName))
                {
                    File.Copy(fileName, sfd.FileName, true);
                    Function.ShowMsg("下载成功!", CYSoft.Common.CYEnumerate.MsgType.OK);
                }
                else {
                    Function.ShowMsg("未找到学生信息模板文件!", CYSoft.Common.CYEnumerate.MsgType.OK);
                    return;
                }
            }
        }

选择文件:

   //选择文件
        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.xls,*.xlsx)|*.xls;*.xlsx";
            if (ofd.ShowDialog(this) == DialogResult.OK) {
                this.btnFile.Text = ofd.FileName;

                ExcelData = null;              

                #region 读取Excel 文件
                //连接字符串   //03版 Microsoft.Jet.OLEDB.4.0
                const string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';Extended Properties='{1};HDR=Yes;IMEX=1'";

                OleDbConnection conn = new OleDbConnection(string.Format(strConn, ofd.FileName, "Excel 8.0"));
                try
                {
                    conn.Open();
                }
                catch
                {
                    conn = new OleDbConnection(string.Format(strConn, ofd.FileName, "Excel 12.0"));
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception ee)
                    {
                        Func.ShowMessage("连接Excel文件错误:" + ee.Message, Func.InfoEnum.HintIE);
                        return;
                    }
                }

                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                DataSet ds = new DataSet();
                foreach (DataRow dr in dt.Rows)
                {
                    string sql = "select * from [" + dr["TABLE_NAME"].ToString() + "]";
                    OleDbDataAdapter aper = new OleDbDataAdapter(sql, conn);                    
                    aper.Fill(ds, dr["TABLE_NAME"].ToString());
                    if (ds.Tables[dr["TABLE_NAME"].ToString()].Columns.Count < 2)
                    {
                        continue;
                    }

                    //dt = myset.Tables[dr["TABLE_NAME"].ToString()];
                    if (ds == null || ds.Tables[0].Rows.Count < 1)
                    {
                        Func.ShowMessage("连接Excel文件错误:", Func.InfoEnum.HintIE);
                        return;
                    }                 
                }               
                conn.Close();
                conn.Dispose();
                #endregion

                ExcelData = ds;
                //校验数据并加载
                InitExcelData2();
                
            }
        }

说明:

数据校验、加载、保存就不写了

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码来实现将 Excel 数据导入到 MySQL 数据库中: ```csharp using System; using System.Data; using System.Data.OleDb; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace ExcelToMySQL { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 设置 Excel 文件路径和连接字符串 string filePath = textBox1.Text; string fileExt = System.IO.Path.GetExtension(filePath); string connString = ""; if (fileExt == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"; } else if (fileExt == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'"; } // 读取 Excel 数据到 DataTable 中 OleDbConnection conn = new OleDbConnection(connString); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn); DataTable dt = new DataTable(); da.Fill(dt); // 将 DataTable 中的数据导入到 MySQL 数据库中 string mysqlConnString = "Server=localhost;Database=test;Uid=root;Pwd=123456;"; MySqlConnection mysqlConn = new MySqlConnection(mysqlConnString); mysqlConn.Open(); foreach (DataRow row in dt.Rows) { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = mysqlConn; cmd.CommandText = "INSERT INTO mytable (id, name, age) VALUES (@id, @name, @age)"; cmd.Parameters.AddWithValue("@id", row["ID"].ToString()); cmd.Parameters.AddWithValue("@name", row["Name"].ToString()); cmd.Parameters.AddWithValue("@age", row["Age"].ToString()); cmd.ExecuteNonQuery(); } mysqlConn.Close(); MessageBox.Show("导入成功!"); } } } ``` 在上面的代码中,需要根据实际情况修改以下变量: - `filePath`:Excel 文件路径 - `connString`:Excel 连接字符串 - `mysqlConnString`:MySQL 连接字符串 - `da.Fill(dt)`:指定要读取的 Excel 工作表名称(这里是 `Sheet1`) - `cmd.CommandText`:指定要插入数据的表名和字段名 另外,需要在 WinForm 窗体中添加一个 `TextBox` 控件和一个 `Button` 控件,并将它们分别命名为 `textBox1` 和 `button1`。当用户点击 `button1` 按钮时,会触发 `button1_Click` 方法,从而执行 Excel 数据导入到 MySQL 数据库的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值