南雄北北

导航

c#下 将DataTable 数据导出到Execl

将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;
            }
        }

posted on 2009-09-10 23:43  南雄北北  阅读(451)  评论(0编辑  收藏  举报