c#使用StreamWriter将DataTable保存到Excel

废话不多说,贴代码:

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文件。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页