找回密码
 会员注册
查看: 189|回复: 0

asp.net导出数据到Excel的两种方法

[复制链接]

1389

主题

5

回帖

496万

积分

管理员

积分
4962992
发表于 2024-2-29 08:12:08 | 显示全部楼层 |阅读模式
  1. public void CreateExcel(DataTable dt,string FileName)//HttpResponse Page.Response
  2. {
  3. string FileType = "application/ms-excel";
  4. Response.Clear();
  5. Response.Charset = "UTF-8";
  6. Response.Buffer = true;
  7. Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  8. Response.AppendHeader("Content-Disposition", "attachment;filename="" + FileName + ".xls"");
  9. Response.ContentType = FileType;
  10. string colHeaders = string.Empty;
  11. colHeaders = '标题'
  12. Response.Output.Write(colHeaders);
  13. colHeaders = string.Empty;
  14. string ls_item = string.Empty;
  15. DataRow[] myRow = dt.Select();
  16. int cl = dt.Columns.Count;
  17. foreach (DataRow row in myRow)
  18. {
  19. int count = 0;
  20. for (int i = 0; i < cl; i++)
  21. {
  22. if (i == (cl - 1))
  23. {
  24. ls_item += row[i].ToString() + "\n";
  25. }
  26. else
  27. {
  28. if(count < 2)
  29. {
  30. ls_item = ls_item + "" + row[i].ToString() + "\t";
  31. }
  32. else
  33. {
  34. ls_item += row[i].ToString() + "\t";
  35. }
  36. }
  37. count++;
  38. }
  39. Response.Output.Write(ls_item);
  40. ls_item = string.Empty;
  41. }
  42. Response.Output.Flush();
  43. Response.End();
  44. }
复制代码

第二种用HttpContext.Current.Response。这种能够解决导出Excel科学记数法的问题。

这个方法的原文链接https://www.cnblogs.com/JsonShare/p/4872173.html

  1. public void CreateExcel_t(DataTable dt, string FileName) {
  2. HttpContext.Current.Response.Clear();
  3. HttpContext.Current.Response.Charset = "UTF-8";
  4. HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
  5. HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
  6. StringBuilder table = new StringBuilder();
  7. table.Append("<table><tr>");
  8. for (int j = 0; j < dt.Columns.Count; j++)
  9. {
  10. table.Append("<td>");
  11. table.Append(dt.Columns[i].Caption.ToString());//表格的标题
  12. table.Append("</td>");
  13. }
  14. table.Append("</tr>");
  15. for (int i = 0 ; i < dt.Rows.Count; i++)
  16. {
  17. table.Append("<tr>");
  18. for (int j = 0; j < dt.Columns.Count; j++)
  19. {
  20. table.Append("<td style='vnd.ms-excel.numberformat:@'>");
  21. table.Append(dt.Rows[i][j].ToString());
  22. table.Append("</td>");
  23. }
  24. table.Append("</tr>");
  25. }
  26. table.Append("</table>");
  27. HttpContext.Current.Response.Write(table);
  28. HttpContext.Current.Response.End();
  29. }
复制代码



来源:https://blog.csdn.net/weixin_42353499/article/details/80522734
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-27 01:34 , Processed in 1.200467 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表