C#数据导出到Excel(或Word)源代码大全(一)

一、DataSet数据集内数据转化为Excel

  1. // 作用:把DataSet数据集内数据转化为Excel、Word文件
  2. // 描述:这些关于Excel、Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后
  3. //        生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之。   
  4. // 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
  5. public void DataSetToExcel(DataSet ds,string FileName)
  6. {
  7.    try
  8.     {
  9.       //Web页面定义
  10.       //System.Web.UI.Page mypage=new System.Web.UI.Page();
  11.        HttpResponse resp;
  12.        resp=HttpContext.Current.Response;
  13.        resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
  14.        resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
  15.        resp.ContentType="application/ms-excel";
  16.       //变量定义
  17.       string colHeaders=null;
  18.       string Is_item=null;
  19.       //显示格式定义
  20.       //文件流操作定义
  21.       //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
  22.       //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
  23.        StringWriter sfw=new StringWriter();
  24.       //定义表对象与行对象,同时用DataSet对其值进行初始化
  25.        System.Data.DataTable dt=ds.Tables[0];
  26.        DataRow[] myRow=dt.Select();
  27.       int i=0;
  28.       int cl=dt.Columns.Count;
  29.       //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
  30.       for(i=0;i<cl;i++)
  31.        {
  32.          //if(i==(cl-1))   //最后一列,加/n
  33.          // colHeaders+=dt.Columns[i].Caption.ToString();
  34.          //else
  35.           colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
  36.        }
  37.        sfw.WriteLine(colHeaders);
  38.       //sw.WriteLine(colHeaders);
  39.       //逐行处理数据
  40.       foreach(DataRow row in myRow)
  41.        {
  42.          //当前数据写入
  43.          for(i=0;i<cl;i++)
  44.           {
  45.           //if(i==(cl-1))
  46.           //    Is_item+=row[i].ToString()+"/n";
  47.           //else
  48.            Is_item+=row[i].ToString()+"/t";
  49.           }
  50.           sfw.WriteLine(Is_item);
  51.          //sw.WriteLine(Is_item);
  52.           Is_item=null;
  53.        }
  54.        resp.Write(sfw);
  55.       //resp.Clear();
  56.        resp.End();
  57.     }
  58.    catch(Exception e)
  59.     {
  60.       throw e;
  61.     }
  62. }

二、DataSet数据集内数据转化为Excel文件(2)

  1. /// <summary>
  2. /// ExportFiles 的摘要说明。
  3. /// 作用:把DataSet数据集内数据转化为Excel文件
  4. /// 描述:导出Excel文件   
  5. /// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
  6. /// </summary>
  7. public class ExportFiles
  8. {
  9.     private string filePath = "";
  10.     public ExportFiles(string excel_path)
  11.      {
  12.         //
  13.         // TODO: 在此处添加构造函数逻辑
  14.         //
  15.          filePath = excel_path;
  16.      }
  17.     /// <summary>
  18.     /// 将指定的Dataset导出到Excel文件
  19.     /// </summary>
  20.     /// <param name="dt"></param>
  21.     /// <returns></returns>
  22.     public bool ExportToExcel(System.Data.DataSet ds, string ReportName)
  23.      {
  24.         if (ds.Tables[0].Rows.Count == 0)
  25.          {
  26.              MessageBox.Show("数据集为空");
  27.          }
  28.          Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
  29.          Workbook xlbook = xlapp.Workbooks.Add(true);
  30.          Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
  31.          Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
  32.          range.MergeCells = true;
  33.          xlapp.ActiveCell.FormulaR1C1 = ReportName;
  34.          xlapp.ActiveCell.Font.Size = 20;
  35.          xlapp.ActiveCell.Font.Bold = true;
  36.          xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
  37.         int colIndex = 0;
  38.         int RowIndex = 2;
  39.         //开始写入每列的标题
  40.         foreach (DataColumn dc in ds.Tables[0].Columns)
  41.          {
  42.              colIndex++;
  43.              xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
  44.          }
  45.         //开始写入内容
  46.         int RowCount = ds.Tables[0].Rows.Count;//行数
  47.         for (int i = 0; i < RowCount; i++)
  48.          {
  49.              RowIndex++;
  50.             int ColCount = ds.Tables[0].Columns.Count;//列数
  51.             for (colIndex = 1; colIndex <= ColCount; colIndex++)
  52.              {
  53.                  xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i, colIndex - 1];
  54.                  xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;
  55.              }
  56.          }
  57.          xlbook.Saved = true;
  58.          xlbook.SaveCopyAs(filePath);
  59.          xlapp.Quit();
  60.          GC.Collect();
  61.         return true;
  62.      }
  63.     public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName)
  64.      {
  65.         if (ds.Tables[0].Rows.Count == 0)
  66.          {
  67.              MessageBox.Show("数据集为空");
  68.          }
  69.         string FileName = filePath;
  70.         //System.Data.DataTable dt = new System.Data.DataTable();
  71.          FileStream objFileStream;
  72.          StreamWriter objStreamWriter;
  73.         string strLine = "";
  74.          objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
  75.          objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
  76.          strLine = ReportName;
  77.          objStreamWriter.WriteLine(strLine);
  78.          strLine = "";
  79.         for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  80.          {
  81.              strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + "           " + Convert.ToChar(9);
  82.          }
  83.          objStreamWriter.WriteLine(strLine);
  84.          strLine = "";
  85.         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
  86.          {
  87.              strLine = strLine + (i + 1) + Convert.ToChar(9);
  88.             for (int j = 1; j < ds.Tables[0].Columns.Count; j++)
  89.              {
  90.                  strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9);
  91.              }
  92.              objStreamWriter.WriteLine(strLine);
  93.              strLine = "";
  94.          }
  95.          objStreamWriter.Close();
  96.          objFileStream.Close();
  97.         //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
  98.         //Workbook xlbook = xlapp.Workbooks.Add(true);
  99.         //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
  100.         //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
  101.         //range.EntireColumn.AutoFit();
  102.         //xlapp.Quit();
  103.         return true;
  104.      }     
  105. }

三、生成XML然后转换成Excel方式

参考资源:http://www.codeproject.com/office/Excel_Export.asp?df=100&forumid=329437&fr=51 (源程序)
优点:
a. 服务端不用安装Excel程序。
b. 支持一定的Excel文件格式设置,比如字体大小、颜色、合并单元格等。
缺点:
a. 与Excel 2000不兼容:由于Excel 2000不支持XML,所以以这种方法生成的Excel文件可能在Excel2000中不兼容(毕竟目前还有不少用户的电脑装的是Excel 2000)。
b. 可能不支持Excel文件页边距的设置;不支持Excel文件横向、纵向的设置;不支持Excel模板;
c. 编程工作量比较大;
d. 生成的文件本质上是XML文件,需要“另存为xls”才能变成真正的Excel文件。
e. 性能是好是坏还不清楚,目前还没真正在项目中用过。希望有用过此方案的朋友能介绍一下这个方案的性能。

四、导出GridView到Excel

  1. //导出GridView到Excel中的关键之处
  2. //用法: ToExcel(GVStaff, TextBox1.Text);
  3. public static void ToExcel(System.Web.UI.Control ctl,string FileName)
  4. {
  5.      HttpContext.Current.Response.Charset ="UTF-8";
  6.      HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
  7.      HttpContext.Current.Response.ContentType ="application/ms-excel";
  8.      HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
  9.      ctl.Page.EnableViewState =false;
  10.      System.IO.StringWriter   tw = new System.IO.StringWriter();
  11.      HtmlTextWriter hw = new HtmlTextWriter(tw);
  12.      ctl.RenderControl(hw);
  13.      HttpContext.Current.Response.Write(tw.ToString());
  14.      HttpContext.Current.Response.End();
  15. }        
  16.      
  17. 必须有下面这句!否则不会通过!
  18. public override void VerifyRenderingInServerForm(Control control)
  19. {
  20.     // Confirms that an HtmlForm control is rendered for
  21. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值