加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

将数据从SQLserver导出到Excel

发布时间:2020-12-12 12:42:58 所属栏目:MsSql教程 来源:网络整理
导读:以下都只是介绍操作的原理,具体要求要在应用中具体分析改变。 1.???????此方法常用在form或者Console Application中,使用时须用要添加Reference,具体做法: ???????? ? 右键点击项目添加 “Add Reference”,在 Tom 组件下,选择 “Microsoft Excel 14.0

以下都只是介绍操作的原理,具体要求要在应用中具体分析改变。

1.???????此方法常用在form或者Console Application中,使用时须用要添加Reference,具体做法:

???????? ?右键点击项目添加“Add Reference”,在Tom组件下,选择“Microsoft Excel 14.0 Object Library”,然后在项目中使用?????

?????????下面注释//it looks like excele table start with 1 not 1

???????? 应该为//it looks like excele table start with 1 not?0????

????????? [csharp]? view plain copy
  1. private?static?void?exportToExcel(DataTable?dt)??
  2. ????????{??
  3. ????????????Excel.Application?excel=new?Excel.Application();??
  4. ????????????excel.Application.Workbooks.Add(true);??
  5. ????????????excel.Visible?=?true;??
  6. ??
  7. ????????????//get?the?columns??
  8. ????????????for?(int?i?=?0;?i?<?dt.Columns.Count;i++?)??
  9. ????????????{??
  10. ????????????????//here?is?started?with?1??
  11. ????????????????//it?looks?like?excele?table?start?with?1?not?1??
  12. ????????????????excel.Cells[1,?i?+?1]?=?dt.Columns[i].ColumnName.ToString();???
  13. ????????????}??
  14. //get?the?data?in?rows??
  15. int?row?=?0;?row?<?dt.Rows.Count;row++?)??
  16. ????????????????int?col?=?0;?col?<?dt.Columns.Count;?col++)??
  17. ????????????????{??
  18. ????????????????????excel.Cells[row+2,?col+1]?=?dt.Rows[row][dt.Columns[col]].ToString();??
  19. ????????????????}??
  20. ????????????}??
  21. //FolderBrowserDialog?path?=?new?FolderBrowserDialog();//打开文件对话框??
  22. ????????????//path.ShowDialog();??
  23. //textBox1.Text?=?path.SelectedPath;//选择文件夹??
  24. //save?excel??
  25. //excel.SaveWorkspace();??
  26. ??
  27. ????????????excel.Quit();??
  28. ????????}??


2. 在web应用中,可通过HttpContext.Response.write()来实现

copy
    protected?void??toExcel(DataTable?da){??
  1. ????????System.Web.HttpContext?context?=?System.Web.HttpContext.Current;??
  2. ????????context.Response.Clear();??
  3. ????????foreach(?DataColumn?colum?in?da.Columns){??
  4. ????????????context.Response.Write(colum.ColumnName+"t");??
  5. ????????}??
  6. ????????context.Response.Write(System.Environment.NewLine);??
  7. foreach?(DataRow?row?in?da.Rows)?{??
  8. int?i?=?0;?i?<?da.Rows.Count;?i++)??
  9. ????????????????context.Response.Write(row[i].ToString()+"t");??
  10. ????????????context.Response.Write(System.Environment.NewLine);??
  11. ????????context.Response.ContentType?=?"application/vnd.ms-excel";??
  12. ????????context.Response.AppendHeader("Content-Disposition",?"attachment;?filename=plan.xls");??
  13. ????????context.Response.End();??
  14. ????} ?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读