public void WriteExcel(DataGridView 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();
MessageBox.Show(ds.Rows.Count+","+ds.ColumnCount);
for (int i = 0; i < ds.ColumnCount; i++)
{
sb.Append(ds.Columns[i].HeaderText + "\t");
}
sb.Append(Environment.NewLine);//每写一行数据后换行
//写内容
for (int j = 0; j < ds.Rows.Count; j++)
{
for (int k = 0; k < ds.ColumnCount; k++)
{
sb.Append(ds.Rows[j].Cells[k].Value.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);
}
}