C# 将dataTable中的数据导出到excel表中

【摘要】 通过IO流的方式进行导出
在winform界面拖一个提交按钮,单击按钮,进入按钮 按钮的内容如下:
`private void ExportExcel_Click(object sender, EventArgs e) { DataGridView myDGV = dataGridView1;: string path = “”; SaveFileDialog sa…

通过IO流的方式进行导出

  1. 在winform界面拖一个提交按钮,单击按钮,进入按钮 按钮的内容如下:
`private void ExportExcel_Click(object sender, EventArgs e) { DataGridView myDGV = dataGridView1;string path = ""; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xls"; saveDialog.Filter = "Excel97-2003 (*.xls)|*.xls|All Files (*.*)|*.*"; saveDialog.ShowDialog(); path = saveDialog.FileName; if (path.IndexOf(":") < 0) return; //判断是否点击取消 try { Thread.Sleep(1000); StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312")); StringBuilder sb = new StringBuilder(); //写入标题 for (int k = 0; k < myDGV.Columns.Count; k++) { if (myDGV.Columns[k].Visible)//导出可见的标题 { //"\t"就等于键盘上的Tab,加个"\t"的意思是: 填充完后进入下一个单元格. sb.Append(myDGV.Columns[k].HeaderText.ToString().Trim() + "\t"); } } sb.Append(Environment.NewLine);//换行 //写入每行数值 for (int i = 0; i <= myDGV.Rows.Count - 1; i++) { System.Windows.Forms.Application.DoEvents(); for (int j = 0; j < myDGV.Columns.Count; j++) { if (myDGV.Columns[j].Visible)//导出可见的单元格 { //注意单元格有一定的字节数量限制,如果超出,就会出现两个单元格的内容是一模一样的. //具体限制是多少字节,没有作深入研究. //   Console.WriteLine(myDGV.Rows[i].Cells[j].Value + "\t"); if (j == 2) { sb.Append("'" + myDGV.Rows[i].Cells[j].Value + "\t"); } else { sb.Append(myDGV.Rows[i].Cells[j].Value + "\t"); } } } sb.Append(Environment.NewLine); //换行 } sw.Write(sb.ToString()); sw.Flush(); sw.Close(); MessageBox.Show(path + ",导出成功", "系统提示", MessageBoxButtons.OK); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

  
 
  1. 注意事项:
    2.1 当dataGridView中的列不完全在datatable中的时候,导出到excel中的时候,空的字段会显示在前面
    2.2 当导出日期时,正常处理会乱码,需要加 ” ’ ” 。如图所示
    在这里插入图片描述
    2.3 需要使用引用
    using System.IO;
    using System.Threading;

文章来源: blog.csdn.net,作者:一只鳄鱼果果,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/m0_46914627/article/details/116274602

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享