C#WinForm 使用StreamWriter导出数据成Excel文件。

来源:互联网 发布:归来。知乎 编辑:程序博客网 时间:2024/05/24 06:33
1:导出数据为Excel文件在开发项目时比较常见的一种需求 。以前对于数据量较小的情况使用 Microsoft.Office.Interop.Excel.Workbooks相关类,编写起来也比较麻烦,对于数据量较大的情况,在此与大家共享使用SteamWriter类输出Excel文件的方法。经过具体测试,通过在程序中使用多线程配置该方法,导出300000行+17列的约130M的数据需要31秒左右。
        /// <summary>        /// 导出文件,使用文件流。该方法使用的数据源为DataTable,导出的Excel文件没有具体的样式。        /// </summary>        /// <param name="dt"></param>        public static string ExportToExcel(System.Data.DataTable dt, string path)        {            KillSpecialExcel();            string result = string.Empty;            try            {                // 实例化流对象,以特定的编码向流中写入字符。                StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));                StringBuilder sb = new StringBuilder();                for (int k = 0; k < dt.Columns.Count; k++)                {                    // 添加列名称                    sb.Append(dt.Columns[k].ColumnName.ToString() + "\t");                }                sb.Append(Environment.NewLine);                // 添加行数据                for (int i = 0; i < dt.Rows.Count; i++)                {                    DataRow row = dt.Rows[i];                    for (int j = 0; j < dt.Columns.Count; j++)                    {                        // 根据列数追加行数据                        sb.Append(row[j].ToString() + "\t");                    }                    sb.Append(Environment.NewLine);                }                sw.Write(sb.ToString());                sw.Flush();                sw.Close();                sw.Dispose();                // 导出成功后打开                //System.Diagnostics.Process.Start(path);            }            catch (Exception)            {                result = "请保存或关闭可能已打开的Excel文件";            }            finally            {                dt.Dispose();            }            return result;        }        /// <summary>        /// 结束进程        /// </summary>        private static void KillSpecialExcel()        {            foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))            {                if (!theProc.HasExited)                {                    bool b = theProc.CloseMainWindow();                    if (b == false)                    {                        theProc.Kill();                    }                    theProc.Close();                }            }        }

B/S 导出:

// 保存错误信息                        GridView gv = new GridView();                        gv.DataSource = dtError;                        gv.DataBind();                        gv.Attributes.Add("style", "vnd.ms-excel.numberformat:@");                        HttpResponse hResponse = this.Response;                        string fileName1 = "新员工格式验证错误统计" + DateTime.Now.ToString("yyyyMMdd");                        hResponse.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName1, System.Text.Encoding.UTF8) + ".xls");                        hResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");                        hResponse.ContentType = "application/ms-excel";                        this.EnableViewState = false;                        StringWriter tw = new StringWriter();                        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);                        gv.RenderControl(hw);                        hResponse.Write(tw);                        hResponse.End();


2 0