动网论坛,站长建站首选,国内使用量最多的论坛软件 动网论坛官方技术讨论区 站长工具 申请属于您自己的免费论坛
首页 | 新闻资讯 | 网站运营 | 网络编程 | 数据库 | 服务器 | 网页设计 | 图像媒体 | 网络应用 | 搜索优化 | 资源下载 | 动网主机 | DVBOX
    本站内  互联网 ASP论坛  ASP.Net论坛  PHP论坛
   .Net → 阅读文章

 怎么由DataSet将数据导入Excel?

作者:郁郁小蝎 来源:中国站长学院 
阅读 2108 人次 , 2006-2-15 14:31:00 

/// <summary>
  /// 将DataSet里所有数据导入Excel.
  /// 需要添加COM: Microsoft Excel Object Library.
  /// using Excel;
  /// </summary>
  /// <param name="filePath"></param>
  /// <param name="ds"></param>
  public static void ExportToExcel(string filePath, DataSet ds)
  {
   object oMissing = System.Reflection.Missing.Value;
   Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
   try
   {
    // 打开Excel文件。以下为Office 2000.
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing,
     oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
     oMissing);
    Excel.Worksheet xlWorksheet;
    // 循环所有DataTable
    for( int i=0; i<ds.Tables.Count; i++ )
    {
     // 添加入一个新的Sheet页。
     xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
     // 以TableName作为新加的Sheet页名。
     xlWorksheet.Name = ds.Tables[i].TableName;
     // 取出这个DataTable中的所有值,暂存于stringBuffer中。
     string stringBuffer = "";
     for( int j=0; j<ds.Tables[i].Rows.Count; j++ )
     {
      for( int k=0; k<ds.Tables[i].Columns.Count; k++ )
      {
      
       stringBuffer += ds.Tables[i].Rows[j][k].ToString();
       if( k < ds.Tables[i].Columns.Count - 1 )
        stringBuffer += "\t";
      }
      stringBuffer += "\n";
     }
     // 利用系统剪切板
     System.Windows.Forms.Clipboard.SetDataObject("");
     // 将stringBuffer放入剪切板。
     System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
     // 选中这个sheet页中的第一个单元格
     ((Excel.Range)xlWorksheet.Cells[1,1]).Select();
     // 粘贴!
     xlWorksheet.Paste(oMissing,oMissing);
     // 清空系统剪切板。
     System.Windows.Forms.Clipboard.SetDataObject("");
    }
    // 保存并关闭这个工作簿。
    xlWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
    xlWorkbook = null;
   }
   catch(Exception ex)
   {
    MessageBox.Show(ex.Message);
   }
   finally
   {
    // 释放...
    xlApp.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
    xlApp = null;
    GC.Collect();
   }
  }
  
 本文Tagsexcel  
 收藏本文  打印本文  论坛讨论  关闭窗口
· 上一篇:用VS.NET2003制作WEB应用程序的安装包
· 下一篇:Visual Basic串口通讯调试方法
· 关于Microsoft.NET Beta1与Visual Studio.NET Alpha不兼容
· asp.net高级教程(二)--- 转换编程思维
· ASP.NET中数据库的操作初步(2)
· 在RichTextBox控件加入图片
· 浅析.Net下的多线程编程


关于本站 | 联系我们 | 业务合作 | 客户案例 | 诚聘英才 | 广告合作 | 收藏本站
海口动网先锋网络科技有限公司版权所有
Copyright © 2000 - 2006 Cndw.Com
中华人民共和国电信与信息服务业务经营许可证编号 琼 ICP 020077