public static void ExportCSV(System.Data.DataTable table, string path)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("导出表格失败,请检查电脑是否已安装Excel。", "提示");
}
StreamWriter writer;
bool comma = false;
int columns = table.Columns.Count;
using (writer = new StreamWriter(path, false, Encoding.UTF8)) ///设置表格编码是UTF8
{
foreach (DataColumn col in table.Columns)
{
if (!comma)
comma = true;
else
writer.Write(',');
writer.Write(col.ColumnName);
}
writer.WriteLine();
foreach (DataRow row in table.Rows)
{
comma = false;
for (int c = 0; c < columns; c++)
{
if (!comma) comma = true;
else writer.Write(',');
writer.Write(row[c].ToString());
}
writer.WriteLine();
}
}
}
---------------------------------------------调用------------
DataTable dt = new DataTable();
dt = ds.Tables[1];
DateTime now = DateTime.Now;
string sFileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "导出数据到";
saveFileDialog.FileName = sFileName + ".csv";
saveFileDialog.ShowDialog();
ExcelHelper.ExportCSV(dt, saveFileDialog.FileName);