c# DataTable导出为excel

 /// <summary>
        /// 将DataTable导出为Excel文件(.xls)
        /// </summary>
        /// <param name="dt">要导出的DataTable</param>
        public static void ExportToExcel(System.Data.DataTable dt)
        {
            if (dt == null) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的电脑未安装Excel");
                return;
            }

            System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
            saveDia.Filter = "Excel|*.xls";
            saveDia.Title = "导出为Excel文件";

            if (saveDia.ShowDialog() == System.Windows.Forms.DialogResult.OK
             && !string.Empty.Equals(saveDia.FileName))
            {
                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];//取得sheet1
                Microsoft.Office.Interop.Excel.Range range = null;

                long totalCount = dt.Rows.Count;
                long rowRead = 0;
                float percent = 0;
                string fileName = saveDia.FileName;

                //写入标题
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                    range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
                    //range.Interior.ColorIndex = 15;//背景颜色
                    range.Font.Bold = true;//粗体
                    range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
                    //加边框
                    range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);

                    //range.ColumnWidth = 4.63;//设置列宽
                    //range.EntireColumn.AutoFit();//自动调整列宽
                    //r1.EntireRow.AutoFit();//自动调整行高
                }

                //写入内容

                for (int r = 0; r < dt.DefaultView.Count; r++)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = dt.DefaultView[r][i];
                        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2, i + 1];
                        range.Font.Size = 9;//字体大小
                        //加边框
                        range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
                        range.EntireColumn.AutoFit();//自动调整列宽
                    }

                    rowRead++;
                    percent = ((float)(100 * rowRead)) / totalCount;
                    System.Windows.Forms.Application.DoEvents();
                }

                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
                if (dt.Columns.Count > 1)
                {
                    range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
                }

                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(fileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    return;
                }

                workbooks.Close();
                if (xlApp != null)
                {
                    xlApp.Workbooks.Close();
                    xlApp.Quit();
                    int generation = System.GC.GetGeneration(xlApp);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
                    xlApp = null;
                    System.GC.Collect(generation);

                }

                GC.Collect();//强行销毁
                #region 强行杀死最近打开的Excel进程

                System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                System.DateTime startTime = new DateTime();
                int m, killId = 0;
                for (m = 0; m < excelProc.Length; m++)
                {
                    if (startTime < excelProc[m].StartTime)
                    {
                        startTime = excelProc[m].StartTime;
                        killId = m;
                    }
                }
                if (excelProc[killId].HasExited == false)
                {
                    excelProc[killId].Kill();
                }

                #endregion
                MessageBox.Show("导出成功!");
            }
        }

  

时间: 2024-11-08 09:12:24

c# DataTable导出为excel的相关文章

DataTable导出到Excel

static DataTable GetTable() { // // Here we create a DataTable with four columns. // DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patien

把DataTable导出为Excel文件

今天项目里遇到了需要把DataTable导出为Excel的问题将解决方案记录在园子备忘 需要一些东西第三方的类库Aspose.Cells此处随意找个下载链接:http://www.cr173.com/soft/66096.html本人不保证该链接的合法性和有效性 说重点,上Demo public bool ExportAsExcel(string URI, DataSet ds) { Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();

DataTable 导出到 Excel 类

底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> /// <param name="dt">数据表</param> /// <param name="captions">要导出的列标题</param> /// <param name="fieldNames&q

DataTable导出到Excel文件

调用方法: ExcelHelper.Export(dtTemp, "供应商App", DlgSave.FileName, "物料文档" , new string[10] { "MatterCode", "MatterName", "MatterType", "MainUnit", "TagModelName", "LotName", "F

C# datatable 导出到Excel

datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt">要导出的DataTable</param> public static void ErrorCrd_ExportToExcel(DataTable dt) { if (dt == null) return; Microsoft.Office.I

将DataTable导出为Excel文件的方法

 需求:前台点击某个按钮,在后台从数据库中获取某DataTable数据到处成Excel文件. 1.Asp按钮控件 两个按钮,分别调用两种导出Excel文件的后台方法. <%--第一种方法--%> <form id="form1" runat="server"> <div> <asp:Button runat="server" OnClick="Btn1_Click" ID="

excel导出 按dataset里的datatable导出一个excel多个sheet 和 datatable导出

//datatable导出 public static void DataTableToExcel(string filename, string sheetName, DataTable table) { //增加序号列 //rui.dbHelper.insert序号(table, 0); IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(sheetName); //设置单元格的样式:水平垂

DataTable导出为Excel

/// <summary> /// 导出Excel Datatable版本 /// </summary> /// <param name="dt">导出的Datatable</param> /// <param name="ExcelName">导出EXCEL的名称 不需要要带有扩展名_xls</param> public static void NewExportExcelScore(Data

Asp.NET中把DataTable导出为Excel ,中文有乱码现象解决办法

//DataTable为要导出的数据表   DataGrid dg = new DataGrid();                dg.DataSource = DataTable;                dg.DataBind(); //如果文件名称有中文,指定编码                string fileName = HttpUtility.UrlEncode("JobHistoryList", Encoding.UTF8).ToString(); //设置