C#之四十三 从DataGridView导出数据到Excel

举报
tea_year 发表于 2021/12/30 00:58:43 2021/12/30
【摘要】 视频课:https://edu.csdn.net/course/detail/27107 publicvoid outExcel(DataGridView gridView){if (gridView.Rows.Count== 0){MessageBox.Show("没有数据可供导出!","提示", MessageBoxButtons...

视频课:https://edu.csdn.net/course/detail/27107


  
  1. publicvoid outExcel(DataGridView gridView)
  2. {
  3. if (gridView.Rows.Count== 0)
  4. {
  5. MessageBox.Show("没有数据可供导出!","提示", MessageBoxButtons.OK,MessageBoxIcon.Information);
  6. return;
  7. }
  8. else
  9. {
  10. SaveFileDialog saveFileDialog= new SaveFileDialog();
  11. saveFileDialog.Filter= "Execl files (*.xls)|*.xls";
  12. saveFileDialog.FilterIndex= 0;
  13. saveFileDialog.RestoreDirectory= true;
  14. saveFileDialog.CreatePrompt= true;
  15. saveFileDialog.Title= "保存为Excel文件";
  16. saveFileDialog.ShowDialog();
  17. if (saveFileDialog.FileName.IndexOf(":")< 0) return; //被点了"取消"
  18. Stream myStream;
  19. myStream= saveFileDialog.OpenFile();
  20. StreamWriter sw= new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
  21. string columnTitle= "";
  22. try
  23. {
  24. //写入列标题
  25. for (inti = 0; i < this.dataGridView1.ColumnCount; i++)
  26. {
  27. if (i> 0)
  28. {
  29. columnTitle+= "\t";
  30. }
  31. columnTitle+= this.dataGridView1.Columns[i].HeaderText;
  32. }
  33. sw.WriteLine(columnTitle);
  34. //写入列内容
  35. for (intj = 0; j
  36. {
  37. string columnValue= "";
  38. for (intk = 0; k < this.dataGridView1.Columns.Count; k++)
  39. {
  40. if (k> 0)
  41. {
  42. columnValue+= "\t";
  43. }
  44. if (this.dataGridView1.Rows[j].Cells[k].Value== null)
  45. columnValue+= "";
  46. else
  47. columnValue+= this.dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
  48. }
  49. sw.WriteLine(columnValue);
  50. }
  51. sw.Close();
  52. myStream.Close();
  53. }
  54. catch (Exceptione)
  55. {
  56. MessageBox.Show(e.ToString());
  57. }
  58. finally
  59. {
  60. sw.Close();
  61. myStream.Close();
  62. }
  63. }
  64. }

 

 

 

 

 

文章来源: aaaedu.blog.csdn.net,作者:tea_year,版权归原作者所有,如需转载,请联系作者。

原文链接:aaaedu.blog.csdn.net/article/details/51558806

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。