C#输出DataTable数据到Excel文件

发布时间:2016-12-11 20:00:52 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"C#输出DataTable数据到Excel文件",主要涉及到C#输出DataTable数据到Excel文件方面的内容,对于C#输出DataTable数据到Excel文件感兴趣的同学可以参考一下。

下面的代码是将DataTable中的数据输出到Excel表格中: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 privatevoid btnExportExcel_Click(objectsender, EventArgs e) {     SaveFileDialog saveDlg =new SaveFileDialog();     saveDlg.DefaultExt ="xls";     saveDlg.Title ="输出断面表格";     saveDlg.Filter ="Excel文件(.xls)|*.xls";     if(saveDlg.ShowDialog()==DialogResult.OK)     {         try         {             stringstrExcelName = saveDlg.FileName;             Excel.Application xlapp =default(Excel.Application);             Excel.Workbook xlbook =default(Excel.Workbook);             Excel.Worksheet xlsheet =default(Excel.Worksheet);             xlapp =new Excel.Application();             xlapp.Visible =false;             xlapp.DisplayAlerts =false;                System.Object missing = Type.Missing;             xlbook = xlapp.Workbooks.Add(missing);             xlsheet = (Excel.Worksheet)xlbook.Worksheets[1];                for(int m = 0; m < dt.Columns.Count;m++ )             {                 xlsheet.Cells[1, m + 1] = dt.Columns[m].ColumnName;             }                for(int i = 0; i < dt.Rows.Count;i++ )             {                 for(int j = 0; j < dt.Columns.Count;j++ )                 {                     xlsheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();                 }             }                xlbook.SaveCopyAs(strExcelName);             xlapp.Workbooks.Close();             xlapp.Quit();             System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp);             xlsheet =null;             xlbook =null;             xlapp =null;                MessageBox.Show("Excel导出成功");            }         catch(Exception ex)         {             MessageBox.Show("保存出错,原因如下:"+ex.Message.ToString());         }     } }

上一篇:开学了
下一篇:ORA-04030: 在尝试分配 8389132 字节 (pga heap,redo read buffer

相关文章

相关评论