EXCEL导出 C#源码-vs2008-粘贴就可用

来源:互联网 发布:世界青年说 韩冰 知乎 编辑:程序博客网 时间:2024/05/19 00:10

 

注:需要在你的程序集中引用Microsoft.Office.Interop.Excel

 

 

#region Excel导出方法
        /// <summary>
        /// Excel导出方法
        /// </summary>
        /// <param name="savePath">保存EXCEL的路径,如"C://目标管理//ab.xls"</param>
        /// <param name="dt1">数据表-可以改为范型集合</param>
        private void ToExcel(string savePath, System.Data.DataTable dt1)
        {
            string filename = savePath;
            System.Data.DataTable dt = dt1;
            Microsoft.Office.Interop.Excel.ApplicationClass xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

            try
            {
                int j = 1;//从第三行开始添数据

                //初始化execl表头
                //worksheet.Cells[1, 1] = "【 " + tableText + " 】";

                //加列头
                worksheet.Cells[1, 1] = "Excel列名1";
                worksheet.Cells[1, 2] = "Excel列名2";
                worksheet.Cells[1, 3] = "Excel列名3";
                worksheet.Cells[1, 4] = "Excel列名4";

                //加列值
                for (int p = 0; p < dt.Rows.Count; p++)
                {
                    worksheet.Cells[j + 1,  1] = dt.Rows[p]["列名"];
                    worksheet.Cells[j + 1, 2] = dt.Rows[p]["列名"];
                    worksheet.Cells[j + 1, 3] = dt.Rows[p]["列名"];
                    worksheet.Cells[j + 1, 4] = dt.Rows[p]["列名"];
                    j++;
                }
                workbook.Saved = true;

                workbook.SaveCopyAs(filename);
            }
            catch (Exception ed)
            {
                throw new Exception(ed.Message);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                worksheet = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                workbooks.Close();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
                workbooks = null;
                xlApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                xlApp = null;
            }
        }
        #endregion

原创粉丝点击