程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 如何用c#將DataTable 數據導出到Execl

如何用c#將DataTable 數據導出到Execl

編輯:C#入門知識

將DataTable 數據導出到Execl格式
源代碼如下:
首先new一個保存的對話框:
 

        private System.Windows.Forms.SaveFileDialog m_objSave = new SaveFileDialog();
//導出數據方法
        public void m_mthExportToExecl()
        {
            this.m_objSave.DefaultExt = "xls";
            this.m_objSave.Filter = "Excel文件(*.xls)|*.xls";

            if (this.m_objSave.ShowDialog() == DialogResult.OK)
            {
                m_mthDoExport(dtFindCharge, m_objSave.FileName);
            }

        }
//具體導出的方法
        private void m_mthDoExport(DataTable dtSource, string strFileName)
        {
            int rowNum = dtSource.Rows.Count;
            int columnNum = dtSource.Columns.Count;
            int rowIndex = 1;
            int columnIndex = 0;

            if (dtSource == null || string.IsNullOrEmpty(strFileName))
            {
                return;
            }
            if (rowNum > 0)
            {
                Excel.Application xlApp = new Excel.ApplicationClass();
                xlApp.DefaultFilePath = "";
                xlApp.DisplayAlerts = true;
                xlApp.SheetsInNewWorkbook = 1;
                Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                //將DataTable的列名導入Excel表第一行
                foreach (DataColumn dc in dtSource.Columns)
                {
                    columnIndex++;
                    xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
                }
                //將DataTable中的數據導入Excel中
                for (int i = 0; i < rowNum; i++)
                {
                    rowIndex++;
                    columnIndex = 0;
                    for (int j = 0; j < columnNum; j++)
                    {
                        columnIndex++;
                        xlApp.Cells[rowIndex, columnIndex] = dtSource.Rows[i][j].ToString();
                    }
                }
                xlBook.SaveCopyAs(strFileName);
                xlApp = null;
                xlBook = null;
            }
        }

    

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved