关闭

asp.net生成csv文件,并在客户端点击下载(文件流直接输出到客户端而不是先生成保存在服务端再下载)

标签: asp.net
611人阅读 评论(0) 收藏 举报
分类:

1>.定义生成csv文件的model

  public class CSVModel
        {
            public int Id { get; set; }
            public string ProductNum { get; set; }
            public string Com { get; set; }
            public string Name { get; set; }
            public string Phone { get; set; }
            public string Email { get; set; }
            public string AddInfo { get; set; }
            public string String1 { get; set; }
            public string String3 { get; set; }
        }

2>.生成csv部分

   public static string SaveAsCSV<T>(string fileName, IList<T> listModel) where T : class, new()
        {
            string results = "";
            try
            {
                StringBuilder sb = new StringBuilder();
                //通过反射 显示要显示的列
                BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识
                Type objType = typeof(T);
                PropertyInfo[] propInfoArr = objType.GetProperties(bf);
                string header = string.Empty;
                List<string> listPropertys = new List<string>();
                foreach (PropertyInfo info in propInfoArr)
                {
                    if (string.Compare(info.Name.ToUpper(), "ID") != 0) //不考虑自增长的id或者自动生成的guid等
                    {
                        if (!listPropertys.Contains(info.Name))
                        {
                            listPropertys.Add(info.Name);
                        }
                        header += info.Name + ",";
                    }
                }
                //这里是要生成的表头
                header = "产品编号" + "," + "公司名称" + "," + "联系人名称" + "," + "联系人电话" + "," + "联系人邮箱" + "," + "联系人地址" + "," + "询价时间" + "," + " 是否查看";
                sb.AppendLine(header.Trim(',')); //csv头

                foreach (T model in listModel)
                {
                    string strModel = string.Empty;
                    foreach (string strProp in listPropertys)
                    {
                        foreach (PropertyInfo propInfo in propInfoArr)
                        {
                            if (string.Compare(propInfo.Name.ToUpper(), strProp.ToUpper()) == 0)
                            {
                                PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);
                                if (modelProperty != null)
                                {
                                    object objResult = modelProperty.GetValue(model, null);
                                    string result = ((objResult == null) ? string.Empty : objResult).ToString().Trim();
                                    if (result.IndexOf(',') != -1)
                                    {
                                        result = "\"" + result.Replace("\"", "\"\"") + "\""; //特殊字符处理 
                                    }
                                    if (!string.IsNullOrEmpty(result))
                                    {
                                        Type valueType = modelProperty.PropertyType;
                                        if (valueType.Equals(typeof(Nullable<decimal>)))
                                        {
                                            result = decimal.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(decimal)))
                                        {
                                            result = decimal.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<double>)))
                                        {
                                            result = double.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(double)))
                                        {
                                            result = double.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<float>)))
                                        {
                                            result = float.Parse(result).ToString("#.#");
                                        }
                                        else if (valueType.Equals(typeof(float)))
                                        {
                                            result = float.Parse(result).ToString("#.#");
                                        }
                                    }
                                    strModel += result + ",";
                                }
                                else
                                {
                                    strModel += ",";
                                }
                                break;
                            }
                        }
                    }
                    strModel = strModel.Substring(0, strModel.Length - 1);
                    sb.AppendLine(strModel);
                }
                string content = sb.ToString();

                results = content;

            }
            catch
            {

            }
            return results;

        }


3>.响应点击事件,查出所需数据并调用上一个方法

 protected void btnImport_Click(object sender, EventArgs e)
        {

            DataSet ds = new BLL.ConsultationPrice().GetList(" 1=1");
            List<CSVModel> db_list = new List<CSVModel>();
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        CSVModel db_model = new CSVModel();
                        db_model.Id = ds.Tables[0].Rows[i]["ProductId"].ToInt();
                        db_model.ProductNum = ds.Tables[0].Rows[i]["ProductNum"].ToString();
                        db_model.Com = ds.Tables[0].Rows[i]["Com"].ToString();
                        db_model.Name = ds.Tables[0].Rows[i]["Name"].ToString();
                        db_model.Phone = ds.Tables[0].Rows[i]["Phone"].ToString();
                        db_model.Email = ds.Tables[0].Rows[i]["Email"].ToString();
                        db_model.AddInfo = ds.Tables[0].Rows[i]["AddInfo"].ToString();
                        db_model.String1 = ds.Tables[0].Rows[i]["String1"].ToString();
                        db_model.String3 = ds.Tables[0].Rows[i]["Int1"].ToInt() == 1 ? "已查看" : "未查看";
                        db_list.Add(db_model);
                    }
                }
            }
            //SaveAsCSV(@"C:\Users\Administrator\Desktop\" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".csv", db_list);
            string OI = SaveAsCSV(@"C:\Users\Administrator\Desktop\" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".csv", db_list);

            //StringBuilder objCSV = AnalysisLayer.LoadChargeInfoToCSVString(ViewStateFrom, ViewStateTo, GenerateSortString());
            string strFile = Server.MapPath("mygod.csv");
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
           string names =  System.DateTime.Now.ToString("在线询价yyyy_MM_dd_HH_mm_ss");
            Response.AppendHeader("content-disposition", "attachment;filename="+names+".csv");
            Response.ContentEncoding = System.Text.Encoding.Default;

            //response.contenttype指定文件类型 能为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文件 
            Response.ContentType = "application/ms-txt";
            this.EnableViewState = false;
            Response.Write(OI.ToString());
            Response.End();



            //Response.Write(OI);
        }

如有问题,请加我QQ:631931078或13501715983 至于验证答案么,是个搞IT的都知道

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4404次
    • 积分:315
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:2篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论