C# WinForm导出Excel方法介绍

// 通过文件流实现

public static void ExportToExcel(DataTable dt, string path)
        {
            System.IO.StreamWriter sw = null;
            try
            {
                long totalCount = dt.Rows.Count;
                sw = new System.IO.StreamWriter(path, false, Encoding.Unicode);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(dt.Columns[i].ColumnName + "\t");
                }
                sb.Append(Environment.NewLine);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        sb.Append(dt.Rows[i][j].ToString() + "\t");
                    }
                    sb.Append(Environment.NewLine);
                }
                sw.Write(sb.ToString());
                sw.Flush();
            }
            catch (System.IO.IOException ioe)
            {
                throw ioe;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
        }



相关:http://www.jb51.net/article/44009.htm

你可能感兴趣的:(C# WinForm导出Excel方法介绍)