DataTable dt_e = DataSet0.Tables[0];
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存为Excel文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream stream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
for (int i = 0; i < dt_e.Rows.Count; i++)
{
if (i > 0)
{
columnTitle += "\t";//或者为逗号
}
//columnTitle += dt_e.Columns[i].HeaderText;//写入列标题
columnTitle += dt_e.Columns[i].Caption.ToString();//写入列标题
}
sw.WriteLine(columnTitle);
for (int j = 0; j < dt_e.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dt_e.Columns.Count; k++)
{
if (k > 0)
{
columnValue += "\t";
}
//columnValue += dt_e.Rows[j].Cells[k].Value.ToString();
columnValue += dt_e.Rows[j][k].ToString();
}
sw.WriteLine(columnValue);
}
sw.Close();
stream.Close();
}
finally
{
sw.Close();
stream.Close();
}
}