Excel和datatable相互操作
/// <summary>
/// Excel文档
/// </summary>
/// <param name="table"></param>
/// <param name="file"></param>
private void dataTableToCsv(DataTable table, string file)
{
string title = "";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
for (int i = 0; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
}
title = title.Substring(0, title.Length - 1) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows)
{
string line = "";
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].ColumnName == "Lastgrnd")
{
line += "'" + row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
else
{
line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
}
line = line.Substring(0, line.Length - 1) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}