当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > 怎么由DataSet将数据导入Excel?

ASP.NET
asp.net DiscuzNT登录,退出的代码
ASP .NET中执行控件(如ImageButton、LinkButton等)命令不刷新页面
Microsoft SQL Server 2005 Express 远程访问设置详述,100%成功篇
使用.NET命令行编译器编译项目(如ASP.NET、C#等)
asp.net 去除viewstate
asp.net repeater实现批量删除
asp.net安全、实用、简单的大容量存储过程分页
asp.net 获取图片高度和宽度实例代码
在GridView中LinkButton的属性的应用(如何不用选中就删除这一行)
关于.net(C#)中的跨进程访问的问题
asp.net request.PathInfo实现的url重写
asp.net SqlDataReader绑定Repeater
ASP.NET 动态写入服务器端控件
Discuz .net版本中的短消息系统
asp.net动态加载用户控件,关于后台添加、修改的思考
.net Cookies安全性实践分析
配置Visual Studio 以调试.net framework源代码
asp.net 大文件上传 之 改版了的SlickUpload.HttpUploadModule(Krystalware.SlickUpload.dll)
asp.net Web站点风格切换的实现
asp.net 用户控件中图片及样式问题

ASP.NET 中的 怎么由DataSet将数据导入Excel?


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 63 ::
收藏到网摘: n/a

/// <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();
   }
  }