废话不多说,贴代码:
public static void Export2Excel(DataTable dtTemp, string fileName, bool append = false, Encoding encoding = null){
if (encoding == null)
{
encoding = Encoding.Default;
}
using (var writer = new StreamWriter(fileName, append, encoding))
{
foreach (DataColumn dc in dtTemp.Columns)
{
writer.Write(dc.ToString());
writer.Write(\'\t\');
}
writer.Write("\r\n");
var values = new object[dtTemp.Columns.Count];
foreach (DataRow drTemp in dtTemp.Rows)
{
values = drTemp.ItemArray;
foreach (var t in values)
{
writer.Write(t.ToString());
writer.Write(\'\t\');
}
writer.Write("\r\n");
}
writer.Write("\r\n");
writer.Close();
}
}
注意就是fileName需要使用xls扩展名,无它。这个方法的限制就是只能生成一个Tab的Excel文件。
Felomeng的技术博客