悟生慧

 

winfrom把数据导出Excel表格

#region 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOutExcel_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcesses())
                {
                    if (thisproc.ProcessName.Equals("EXCEL"))
                    {
                        thisproc.Kill();   //终止程序
                    }
                }


                Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();

                System.Data.DataTable ds;
                DataTableChangeDt();
                ds = newtb;


                int row_index, col_index;
                row_index = 1;
                col_index = 1;

                excel.Workbooks.Add(true);

                if (ds.Columns.Contains("tsiid"))
                {
                    ds.Columns.Remove(ds.Columns["tsiid"]);
                }
                if (ds.Columns.Contains("tsc_id"))
                {
                    ds.Columns.Remove(ds.Columns["tsc_id"]);
                }
                if (ds.Columns.Contains("tcs_id"))
                {
                    ds.Columns.Remove(ds.Columns["tcs_id"]);
                }
                ////导出Excle后显示的列名
                for (int i = 0; i < SumColumnsOld.Length; i++)
                {
                    excel.Cells[1, i + 1] = SumColumnsOld[i].ToString();
                }
                excel.Cells[1, SumColumnsOld.Length + 1] = "总计";
                //excel.Cells[1, 2] = "学员卡号";
                //excel.Cells[1, 3] = "班级类型";
                //excel.Cells[1, 4] = "学员班级";
                //excel.Cells[1, 5] = "发卡金额";
                //excel.Cells[1, 6] = "开始时间";
                //excel.Cells[1, 7] = "结束时间";
                //excel.Cells[1, 8] = "剩余次数";
                //excel.Cells[1, 9] = "状态";
                //excel.Cells[1, 10] = "教练";
                //excel.Cells[1, 11] = "是否结算";
                foreach (DataRow dr in ds.Rows)
                {
                    col_index = 0;

                    foreach (DataColumn dc in ds.Columns)
                    {

                        excel.Cells[row_index + 1, col_index + 1] = dr[dc];

                        col_index++;

                        System.Windows.Forms.Application.DoEvents();
                    }

                    row_index++;

                }
                excel.Visible = true;
            }
            catch { }
        }

//using Microsoft.Office.Interop.Excel;

posted on 2011-06-07 16:15  悟生慧  阅读(1979)  评论(0编辑  收藏  举报

导航