欢迎光临!

private void ExportExcel(System.Data.DataTable ds, string strExcelFileName)
        {
            object objOpt = Missing.Value;
            Excel.Application excel = new Excel.Application();
            excel.Visible = true;
            _Workbook wkb = excel.Workbooks.Add(objOpt);
            _Worksheet wks = (_Worksheet)wkb.ActiveSheet;

            wks.Visible = XlSheetVisibility.xlSheetVisible;

            int rowIndex = 1;
            int colIndex = 0;

            System.Data.DataTable table = ds;
            foreach (DataColumn col in table.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }

            foreach (DataRow row in table.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach (DataColumn col in table.Columns)
                {
                    colIndex++;
                    excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                }
            }
            try
            {
                wkb.SaveAs(string.Format("{0}\{1}", System.Windows.Forms.Application.StartupPath, strExcelFileName), objOpt, null, null, false, false, XlSaveAsAccessMode.xlNoChange, ConflictOption.OverwriteChanges, null, null, null, null);

            }
            catch
            {
            }
            finally
            {
                wkb.Close(false, objOpt, objOpt);
                excel.Quit();
            }
        }

 

posted on 2008-10-20 11:34  花拉子米  阅读(202)  评论(0编辑  收藏  举报
版权所有