SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls) |*.xls ";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到 ";
//saveFileDialog.ShowDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("GB2312"));
string str = " ";
try
{
//写标题
for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "/t ";
}
str += this.dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < this.dataGridView1.RowCount - 1; j++)
{
string tempStr = " ";
for (int k = 0; k < this.dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "/t ";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}