SaveFileDialog saveFileDialog = new SaveFileDialog();
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();
int ColumnCount = 3;
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.Unicode);
string str = "";
try
{
for (int i = 0; i < ColumnCount; i++)
//写标题-------------------------------
{
if (i > 0)
{
str += "\t";
}
str += dataGridView2.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView2.Rows.Count; j++)
//写内容--------------------------------
{
string tempStr = "";
for (int k = 0; k < ColumnCount; k++)
{
if (k > 0)
{
tempStr += "\t";
if (k == 1)
{
tempStr += "'";
}
}
tempStr += dataGridView2.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
// MessageBox.Show("导出成功!","系统提示");
}