0
点赞
收藏
分享

微信扫一扫

C# excel数据导入

sullay 2022-04-06 阅读 68


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 计算员工考勤信息

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            this.openFileDialog1.DefaultExt = "xls";

            this.openFileDialog1.Filter = "Excel文件 (*.xls)|*.xls|(*.csv)|*.csv";

            this.saveFileDialog1.DefaultExt = "xls";

            this.saveFileDialog1.Filter = "Excel文件 (*.xls)|*.xls|(*.csv)|*.csv";

        }

       string url="";

       string fileName="";//excel文件名

        //选择excel表

        private void btnBrowsing_Click(object sender, EventArgs e)

        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)

            {

                this.txtUrl.Text = this.openFileDialog1.FileName;

                url=txtUrl.Text;

                fileName=url.Substring(url.LastIndexOf("//"));

            }

        }

        //导入excel表

        private void btnExport_Click(object sender, EventArgs e)

        {

            if (this.txtUrl.Text.Trim() == "")

            {

                MessageBox.Show("请选择excel表!");

            }

            else

            {

                //导入excel

              this.panel1.Visible = true;

              ExcelToDB(url);

            }

         }

        /// <summary>

        /// excel数据导入

        /// </summary>

        /// <param name="path">excel文件路径</param>

        public void ExcelToDB(string path)

        {

            DataSet ds = new DataSet();

            string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=/"Excel 8.0;HDR=Yes;IMEX=1/"", path);

            OleDbConnection connection = new OleDbConnection(connectionString);

            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [预定表$]", connection);

            adapter.Fill(ds);

            this.dataGridView1.DataSource = ds.Tables[0];

        }

        //导出excel表

        private void btnDerived_Click(object sender, EventArgs e)

        {

        }

        public void Bind(DataGridView dv,DataSet ds)

        {

            dv.DataSource = ds.Tables["ExcelInfo"];

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            DialogResult result = MessageBox.Show("确定要离开吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            if (result == DialogResult.OK)

            {

                Application.Exit();

            }

            else

            {

                return;

            }

        }

    }

}


举报

相关推荐

0 条评论