Winform(C#)操作Excel(数据分组应用)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;
using Microsoft.Office.Interop;

namespace HeXieRandomGroup
{
    public partial class RandomGroup : Form
    {
        private DataSet myDataSet;
        private DataTable GroupDt1, GroupDt2, GroupDt3, GroupDt4, GroupDt5;
        private Thread thread;
        private object m_objOpt = System.Reflection.Missing.Value;
        public RandomGroup()
        {
            RandomGroup.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void ConectToxsl_Click(object sender, EventArgs e)
        {
            GetConnect();
            this.Start.Enabled = true;
        }

        private void GetConnect()
        {
            try
            {
                string strCon = " Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath.ToString() + @"/hexie.xls; Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
                OleDbConnection myConn = new OleDbConnection(strCon);
                string strCom = "SELECT * FROM [Sheet1$]";
                myConn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
                myDataSet = new DataSet();
                myCommand.Fill(myDataSet, "[Sheet1$]");
                myConn.Close();
                MessageBox.Show("连接成功!");
                this.ConectToxsl.Enabled = false;
                dataGridView1.DataSource = myDataSet.Tables[0].DefaultView;
            }
            catch (OleDbException e)
            {
                MessageBox.Show("请确认hexie.xls表存在!" + e.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show("链接失败" + e.Message);
            }
        }

        private void Start_Click(object sender, EventArgs e)
        {
            if (myDataSet.Tables[0].Rows.Count > 0)
            {
                mythread();
                this.Start.Enabled = false;

            }
            else
            {
                MessageBox.Show("对不起请确认数据表中有数据!");
            }

        }

        private void deldataset(string str)
        {
            for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
            {
                if (label1.Text == myDataSet.Tables[0].Rows[i][0].ToString())
                {
                    myDataSet.Tables[0].Rows.RemoveAt(i);
                }
            }
        }

        private void mythread()
        {
            thread = new Thread(new ThreadStart(GetPick));
            thread.Start();
        }
        private void GetPick()
        {
            Random autoRand = new Random();
            int n, m, group;
            group = 1;
            m = myDataSet.Tables[0].Rows.Count;

            GroupDt1 = myDataSet.Tables.Add("Group1");

            GroupDt1.Columns.Add("Name", typeof(String));
            GroupDt1.Columns.Add("Address", typeof(String));

            GroupDt2 = myDataSet.Tables.Add("Group2");

            GroupDt2.Columns.Add("Name", typeof(String));
            GroupDt2.Columns.Add("Address", typeof(String));

            GroupDt3 = myDataSet.Tables.Add("Group3");

            GroupDt3.Columns.Add("Name", typeof(String));
            GroupDt3.Columns.Add("Address", typeof(String));

            GroupDt4 = myDataSet.Tables.Add("Group4");

            GroupDt4.Columns.Add("Name", typeof(String));
            GroupDt4.Columns.Add("Address", typeof(String));

            GroupDt5 = myDataSet.Tables.Add("Group5");

            GroupDt5.Columns.Add("Name", typeof(String));
            GroupDt5.Columns.Add("Address", typeof(String));



            for (int i = 0; i < m; i++)
            {
                n = (int)((m - i) * autoRand.NextDouble());
                label1.Text = myDataSet.Tables[0].Rows[n][0].ToString();
                DataRow row;
                switch (group)
                {
                    case 1:
                        listBox1.Items.Add(myDataSet.Tables[0].Rows[n][0].ToString());

                        row = GroupDt1.NewRow();
                        row["Name"] = myDataSet.Tables[0].Rows[n][0].ToString();
                        row["Address"] = myDataSet.Tables[0].Rows[n][1].ToString();
                        GroupDt1.Rows.Add(row);
                        group++;
                        break;
                    case 2:
                        listBox2.Items.Add(myDataSet.Tables[0].Rows[n][0].ToString());

                        row = GroupDt2.NewRow();
                        row["Name"] = myDataSet.Tables[0].Rows[n][0].ToString();
                        row["Address"] = myDataSet.Tables[0].Rows[n][1].ToString();
                        GroupDt2.Rows.Add(row);
                        group++;
                        break;
                    case 3:
                        listBox3.Items.Add(myDataSet.Tables[0].Rows[n][0].ToString());

                        row = GroupDt3.NewRow();
                        row["Name"] = myDataSet.Tables[0].Rows[n][0].ToString();
                        row["Address"] = myDataSet.Tables[0].Rows[n][1].ToString();
                        GroupDt3.Rows.Add(row);
                        group++;
                        break;
                    case 4:
                        listBox4.Items.Add(myDataSet.Tables[0].Rows[n][0].ToString());

                        row = GroupDt4.NewRow();
                        row["Name"] = myDataSet.Tables[0].Rows[n][0].ToString();
                        row["Address"] = myDataSet.Tables[0].Rows[n][1].ToString();
                        GroupDt4.Rows.Add(row);
                        group++;
                        break;
                    default:
                        listBox5.Items.Add(myDataSet.Tables[0].Rows[n][0].ToString());

                        row = GroupDt5.NewRow();
                        row["Name"] = myDataSet.Tables[0].Rows[n][0].ToString();
                        row["Address"] = myDataSet.Tables[0].Rows[n][1].ToString();
                        GroupDt5.Rows.Add(row);
                        group = 1;
                        break;
                }
                deldataset(label1.Text);
                Thread.Sleep(10);

            }
            BtnExt.Enabled = true;
            label1.Text = "成功分组";
            MessageBox.Show("成功分组");


        }

        private void BtnExt_Click(object sender, EventArgs e)
        {
            ExportToExcel(myDataSet, "hexieGroup");
        }


        public void ExportToExcel(DataSet ds, string strExcelFileName)
        {
            if (ds.Tables.Count == 0 || strExcelFileName == "") return;
            doExport(ds, strExcelFileName);
        }


        private void doExport(DataSet ds, string strExcelFileName)
        {

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);
            excel.Visible = false;

            for (int i = 1; i < ds.Tables.Count; i++)
            {
                int rowIndex = 1;
                int colIndex = 0;
                Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveWorkbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                //Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveWorkbook.Sheets[1];

                ws.Select(Type.Missing);
                ws.Name = "Group" + i.ToString();

                System.Data.DataTable table = ds.Tables[i];

                foreach (DataColumn col in table.Columns)
                {

                    colIndex++;
                    ws.Cells[1, colIndex] = col.ColumnName;
                }

                foreach (DataRow row in table.Rows)
                {
                    rowIndex++;
                    colIndex = 0;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        ws.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                    }
                }

                //ws.SaveAs("HexieGroup.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

            }
          
            excel.ActiveWorkbook.SaveAs(Application.StartupPath.ToString() + @"/HexieGroup.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

            System.Diagnostics.Process.Start("explorer.exe", Application.StartupPath.ToString());//打开目录

            excel.Quit();
            excel = null;

            GC.Collect();//垃圾回收
            myDataSet.Clear();
            BtnExt.Enabled = false;
            MessageBox.Show("导出完毕!");
            //KillWordProcess();
        }

        private void RandomGroup_Load(object sender, EventArgs e)
        {
            this.Start.Enabled = false;
            this.BtnExt.Enabled = false;
        }
        public void KillWordProcess()
        {
            int ProceedingCount = 0;
            try
            {
                System.Diagnostics.Process[] ProceddingCon = System.Diagnostics.Process.GetProcesses();
                foreach (System.Diagnostics.Process IsProcedding in ProceddingCon)
                {
                    if (IsProcedding.ProcessName.ToUpper() == "EXCEL")
                    {
                        ProceedingCount += 1;
                        IsProcedding.Kill();
                    }
                }
            }
            catch (System.Exception err)
            {
                MessageBox.Show(err.Message + "/r" + "(" + err.Source + ")" + "/r" + err.StackTrace);
            }
        }
    }
}

你可能感兴趣的:(C#2005)