码迷,mamicode.com
首页 > 其他好文 > 详细

StreamWriter(dataset)导出EXCEL

时间:2015-12-15 14:34:38      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:

 public void WriteExcel(DataSet ds, string path)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
 
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = false;
                saveFileDialog.Title = "导出Excel文件到";
                saveFileDialog.FileName = path;
 
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
 
                    Stream myStream;
                    myStream = saveFileDialog.OpenFile();
 
                    StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("gb2312"));
                    StringBuilder sb = new StringBuilder();
                    for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
                    {
                        sb.Append(ds.Tables[0].Columns[k].ColumnName.ToString() + "\t");
                    }
                    sb.Append(Environment.NewLine);
 
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            sb.Append(ds.Tables[0].Rows[i][j].ToString() + "\t");
                        }
                        sb.Append(Environment.NewLine);//每写一行数据后换行
                    }
                    sw.Write(sb.ToString());
                    sw.Flush();
                    sw.Close();//释放资源
                    KillSpecialExcel();
                    MessageBox.Show("已经生成指定Excel文件!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

StreamWriter(dataset)导出EXCEL

标签:

原文地址:http://www.cnblogs.com/zx66/p/5047909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!