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或352167311