north911 发表于 2010-4-24 14:35:00

[求助]DataGridView数据导出到Excel的问题

哪位知道用流的方法把DataGridView数据导出到Excel时,如何写入指定的sheet中呢
      public static void DataGridViewToExcel(DataGridView dgv)
      {
            
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.CheckFileExists = false;
            dlg.CheckPathExists = false;
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";
                try
                {
                  //写入列标题   
                  for (int i = 0; i0)
                        {
                            columnTitle += "\t";
                        }
                        columnTitle += dgv.Columns.HeaderText;
                  }
                  sw.WriteLine(columnTitle);
                  //写入列内容   
                  for (int j = 0; j0)
                            {
                              columnValue += "\t";
                            }
                            if (dgv.Rows.Cells.Value == null)
                              columnValue += "";
                            else
                              columnValue += dgv.Rows.Cells.Value.ToString().Trim();
                        }
                        sw.WriteLine(columnValue);
                  }
                  sw.Close();
                  myStream.Close();
                }
                catch (Exception e)
                {
                  MessageBox.Show(e.ToString());
                }
                finally
                {
                  sw.Close();
                  myStream.Close();
                }
            }
      }

雪山飞狐_lzh 发表于 2010-4-24 18:55:00

Google:Xml Excel

north911 发表于 2010-4-25 22:48:00

版主是说用流的方法不好吗?
页: [1]
查看完整版本: [求助]DataGridView数据导出到Excel的问题