asp.net生成csv文件代码

作者:袖梨 2022-06-25

using system.web;

public class sdsavecsv
{
        ///


        /// 构造函数
        ///

        /// httpresponse对象
        public sdsavecsv(httpresponse response)
        {
            this.response = response;
        }
        ///
        /// 输入出文件
        ///

        /// 文件名称
        /// 文件内容
        /// 成功/失败
        public bool outfile(string fullpath, string content)
        {
            bool retvalue = false;
            try
            {
                this.response.buffer = true;
                this.response.clear();
                this.response.charset = system.text.encoding.default.bodyname;
                this.response.contentencoding = system.text.encoding.getencoding("gb2312");//gb2312用excel打开时,没有乱码。
                this.response.appendheader("content-disposition", "attachment;filename=" + fullpath);
                this.response.contenttype = "application/ms-excel";
                this.response.output.write(content);
                this.response.flush();
                this.response.end();
                retvalue = true;
            }
            catch (exception ex)
            {
                retvalue = false;
                throw new applicationexception(string.format("输出数据csv出错:{0}",fullpath), ex);
            }
            return retvalue;
        }
}


//===============================以下为调用方法
     stringbuilder sbfile = new stringbuilder();
     sbfile.append("商户,蛋名称,蛋id,时间,累计领蛋人数,累计发蛋量");
     sbfile.appendline();//换行
     foreach (datarow row in ds.tables[0].rows)
                {
                    sbfile.appendformat("{0},{1},{2},{3},{4},{5}", eggmerchants1.merchantname, row["eggname"], row["rowid"], row["date"], row["pep"], row["num"]);
                    sbfile.appendline();
                }
     new sdsavecsv(this.response).outfile(string.format("fetchegg({0}).csv",datetime.now), sbfile.tostring());

相关文章

精彩推荐