1. 程式人生 > >C# winform 讀取excel

C# winform 讀取excel

namespace myTool
{
    partial class Form1
    {
        /// <summary>
        /// 必需的設計器變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的程式碼

        /// <summary>
        /// 設計器支援所需的方法 - 不要修改
        /// 使用程式碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnExport001 = new System.Windows.Forms.Button();
            this.txtPath001 = new System.Windows.Forms.TextBox();
            this.txtSql = new System.Windows.Forms.RichTextBox();
            this.txtPath002 = new System.Windows.Forms.TextBox();
            this.btnExport002 = new System.Windows.Forms.Button();
            this.btnSql = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnExport001
            // 
            this.btnExport001.Location = new System.Drawing.Point(665, 10);
            this.btnExport001.Name = "btnExport001";
            this.btnExport001.Size = new System.Drawing.Size(75, 23);
            this.btnExport001.TabIndex = 0;
            this.btnExport001.Text = "1匯入貨區";
            this.btnExport001.UseVisualStyleBackColor = true;
            this.btnExport001.Click += new System.EventHandler(this.btnExport001_Click);
            // 
            // txtPath001
            // 
            this.txtPath001.Location = new System.Drawing.Point(12, 12);
            this.txtPath001.Name = "txtPath001";
            this.txtPath001.Size = new System.Drawing.Size(647, 21);
            this.txtPath001.TabIndex = 1;
            // 
            // txtSql
            // 
            this.txtSql.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.txtSql.Location = new System.Drawing.Point(12, 101);
            this.txtSql.Name = "txtSql";
            this.txtSql.Size = new System.Drawing.Size(728, 229);
            this.txtSql.TabIndex = 2;
            this.txtSql.Text = "";
            // 
            // txtPath002
            // 
            this.txtPath002.Location = new System.Drawing.Point(12, 45);
            this.txtPath002.Name = "txtPath002";
            this.txtPath002.Size = new System.Drawing.Size(647, 21);
            this.txtPath002.TabIndex = 4;
            // 
            // btnExport002
            // 
            this.btnExport002.Location = new System.Drawing.Point(665, 43);
            this.btnExport002.Name = "btnExport002";
            this.btnExport002.Size = new System.Drawing.Size(75, 23);
            this.btnExport002.TabIndex = 3;
            this.btnExport002.Text = "2匯入貨位";
            this.btnExport002.UseVisualStyleBackColor = true;
            this.btnExport002.Click += new System.EventHandler(this.btnExport002_Click);
            // 
            // btnSql
            // 
            this.btnSql.Location = new System.Drawing.Point(665, 72);
            this.btnSql.Name = "btnSql";
            this.btnSql.Size = new System.Drawing.Size(75, 23);
            this.btnSql.TabIndex = 5;
            this.btnSql.Text = "3生成sql";
            this.btnSql.UseVisualStyleBackColor = true;
            this.btnSql.Click += new System.EventHandler(this.btnSql_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(752, 342);
            this.Controls.Add(this.btnSql);
            this.Controls.Add(this.txtPath002);
            this.Controls.Add(this.btnExport002);
            this.Controls.Add(this.txtSql);
            this.Controls.Add(this.txtPath001);
            this.Controls.Add(this.btnExport001);
            this.Name = "Form1";
            this.Text = "小工具";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnExport001;
        private System.Windows.Forms.TextBox txtPath001;
        private System.Windows.Forms.RichTextBox txtSql;
        private System.Windows.Forms.TextBox txtPath002;
        private System.Windows.Forms.Button btnExport002;
        private System.Windows.Forms.Button btnSql;
    }
}

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 myTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();

            this.txtPath001.ReadOnly = true;
            this.txtPath002.ReadOnly = true;
        }

        public string GetExcelFilePath()
        {
            OpenFileDialog tmp = new OpenFileDialog();
            tmp.Filter = @"Excel檔案 (*.xlsx)|*.xlsx";
            tmp.FilterIndex = 1;
            tmp.RestoreDirectory = true;
            if (tmp.ShowDialog() == DialogResult.OK)
            {
                return tmp.FileName;
            }
            else
            {
                return "";
            }
        }

        public DataTable Excel2Dt(string filePath, int sheetIndex = 0, int colNameIndex = 0, int rowDataIndex = 1)
        {
            string fileType = System.IO.Path.GetExtension(filePath).ToLower();
            string connStr = "";
            if (fileType.ToLower() == ".xls")
            {
                connStr = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            }
            else if (fileType.ToLower() == ".xlsx")
            {
                connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            }
            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connStr))
            {
                conn.Open();
                DataTable sheetsName = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                string sheetName = sheetsName.Rows[sheetIndex]["TABLE_NAME"].ToString();
                sheetName = sheetName.Replace("$", "");

                System.Data.OleDb.OleDbDataAdapter ada = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + sheetName + "$]", connStr);
                DataSet dst = new DataSet();
                ada.Fill(dst);

                //處理返回正確的dt
                DataTable dt = new DataTable();
                dt.TableName = sheetName;

                //讀取列名
                for (int i = 0; i < dst.Tables[0].Columns.Count; i++)
                {
                    DataColumn dc = new DataColumn();
                    dc.DataType = dst.Tables[0].Columns[i].DataType;
                    dc.ColumnName = dst.Tables[0].Rows[colNameIndex][i].ToString();//第1行為列名稱
                    dt.Columns.Add(dc);
                }

                //讀取行資料
                for (int j = rowDataIndex; j < dst.Tables[0].Rows.Count; j++)
                {
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < dst.Tables[0].Columns.Count; i++)
                    {
                        dr[i] = dst.Tables[0].Rows[j][i];
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }

        DataTable result_DISTRICT;
        private void btnExport001_Click(object sender, EventArgs e)
        {
            string path = this.GetExcelFilePath();
            if (path != "")
            {
                this.txtPath001.Text = path;
                result_DISTRICT = new DataTable();
                result_DISTRICT = this.Excel2Dt(path);
            }
        }

        DataTable result_LOC;
        private void btnExport002_Click(object sender, EventArgs e)
        {
            string path = this.GetExcelFilePath();
            if (path != "")
            {
                this.txtPath002.Text = path;
                result_LOC = new DataTable();
                result_LOC = this.Excel2Dt(path);
            }
        }

        private void btnSql_Click(object sender, EventArgs e)
        {
            if (result_DISTRICT == null)
            {
                MessageBox.Show("無資料01");
                return;
            }
            if (result_DISTRICT.Rows.Count == 0)
            {
                MessageBox.Show("無資料02");
                return;
            }

            string sql = "";
            for (int i = 0; i < result_DISTRICT.Rows.Count; i++)//貨區
            {
                string INV_ORG_ID = result_DISTRICT.Rows[i]["INV_ORG_ID"].ToString().Trim();
                string INV_ID = result_DISTRICT.Rows[i]["INV_ID"].ToString().Trim();
                string DISTRICT_CODE = result_DISTRICT.Rows[i]["DISTRICT_CODE"].ToString().Trim();
                string DISTRICT_NAME = result_DISTRICT.Rows[i]["DISTRICT_NAME"].ToString().Trim();
                string DISTRICT_DESC = result_DISTRICT.Rows[i]["DISTRICT_DESC"].ToString().Trim();
                string DISTRICT_ID = Guid.NewGuid().ToString("N").ToUpper().Trim();
                sql += @"



                    INSERT INTO INV_DISTRICT(INV_ORG_ID,INV_ID,DISTRICT_CODE,DISTRICT_NAME,DISTRICT_DESC,ID) VALUES('"
                    + INV_ORG_ID + @"','"
                    + INV_ID + @"','"
                    + DISTRICT_CODE + @"','"
                    + DISTRICT_NAME + @"','"
                    + DISTRICT_DESC + @"','"
                    + DISTRICT_ID + @"');";

                for (int k = 0; k < result_LOC.Rows.Count; k++)
                {
                    string tmp_INV_ORG_ID = result_LOC.Rows[k]["INV_ORG_ID"].ToString().Trim();
                    string tmp_LOC_CODE = result_LOC.Rows[k]["LOC_CODE"].ToString().Trim();
                    string tmp_LOC_NAME = result_LOC.Rows[k]["LOC_NAME"].ToString().Trim();
                    string tmp_LOC_DESC = result_LOC.Rows[k]["LOC_DESC"].ToString().Trim();
                    string tmp_DISTRICT_CODE = result_LOC.Rows[k]["DISTRICT_CODE"].ToString().Trim();
                    if (INV_ORG_ID == tmp_INV_ORG_ID && DISTRICT_CODE == tmp_DISTRICT_CODE)//匹配貨區
                    {
                        sql += @"
                            INSERT INTO INV_LOC(INV_ORG_ID,LOC_CODE,LOC_NAME,LOC_DESC,DISTRICT_ID,DISTRICT_CODE) VALUES('"
                            + tmp_INV_ORG_ID + @"','"
                            + tmp_LOC_CODE + @"','"
                            + tmp_LOC_NAME + @"','"
                            + tmp_LOC_DESC + @"','"
                            + DISTRICT_ID + @"','"
                            + tmp_DISTRICT_CODE + @"');";
                    }
                }
            }

            this.txtSql.Text = sql;
        }
    }
}