日期:2014-05-16  浏览次数:20751 次

如果gridview导出excel文件时,这个文件名是存在且处于打开状态时怎么处理?
下面是一段excel导出的程序:
  private void buttonExcle_Click(object sender, EventArgs e)
  {
  SaveFileDialog saveFileDialog = new SaveFileDialog();
  DfWeb web = new DfWeb(new P101001Service(), this);
  P101001DataSet dset = (P101001DataSet)web.Execute("GetDayListBySearch");
  _griddata = dset.DayList;
  dfDataGridView1.DataSource = _griddata;

  saveFileDialog.Filter = "Execl files (*.xls)|*.xls";

  saveFileDialog.FilterIndex = 0;

  saveFileDialog.RestoreDirectory = true;

  saveFileDialog.CreatePrompt = true;

  saveFileDialog.Title = "Export Excel File To";
  if (saveFileDialog.ShowDialog() == DialogResult.Cancel)  
  { 
  return;
  }
  Stream myStream;

  myStream = saveFileDialog.OpenFile();

  StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));

  StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

  string str = "";
  try
  {
  for (int i = 0; i < dfDataGridView1.ColumnCount; i++)
  {
  if (i > 0)
  {

  str += "\t";

  }
  str += dfDataGridView1.Columns[i].HeaderText;

  }
  sw.WriteLine(str);

  写内容

  for (int j = 0; j < dfDataGridView1.Rows.Count; j++)
  {

  string tempStr = "";

  for (int k = 0; k < dfDataGridView1.Columns.Count; k++)
  {
  if (k > 0)
  {
  tempStr += "\t";
  }
  object value = dfDataGridView1.Rows[j].Cells[k].Value;
  if (value == null)
  {
  value = string.Empty;
  }
  tempStr += value.ToString();

  }
  sw.WriteLine(tempStr);
  }

  sw.Close();
  myStream.Close();
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.ToString());

  }
  finally
  {
  sw.Close();
  myStream.Close();
  }
  }
如果gridview导出excel文件时,这个文件名是存在且处于打开状态时怎么处理?如果不处理,程序将会崩溃。
求各位大侠鼎力帮助。

------解决方案--------------------
你将if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
Stream myStream;

myStream = saveFileDialog.OpenFile();

StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312&qu