標籤:blog http os 檔案 io for re c
asp mvc 匯出txt 檔案泛型方法分享:
public static void ExportFile<T>(T obj) { StringBuilder str = new StringBuilder(); //列出obj 對象中的所有屬性 System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties(); if (properties != null && properties.Length > 0) { // 局部變數 用來判斷迴圈次數,輸出換行和逗號 int j = 0; foreach (var item in properties) { // 擷取屬性值 object objvalue = item.GetValue(obj, null); //是否是泛型型別 if (item.PropertyType.IsGenericType) { Type objType = objvalue.GetType(); // 擷取泛型集合總數 int count = Convert.ToInt32(objType.GetProperty("Count").GetValue(objvalue, null)); // 遍曆集合 for (int i = 0; i < count; i++) { object listitem = objType.GetProperty("Item").GetValue(objvalue, new object[] { i }); System.Reflection.PropertyInfo[] myPros = listitem.GetType().GetProperties(); // 局部變數 用來判斷迴圈次數,輸出換行和逗號 int k = 0; // 遍曆集合中的屬性 foreach (var m in myPros) { // 屬性名稱 //str.Append(m.Name); //str.Append(","); //str.Append("\t"); if (m.GetValue(listitem, null) != null) { // 屬性值 str.Append(m.GetValue(listitem, null)); } else { str.Append("空值"); } // 換行 if ((k+1) % 2 == 0) { str.Append("\n"); } // 輸出 逗號 else if (k % 2 == 0) { str.Append(","); } k++; } } } // 非泛型型別 else { // 屬性名稱 //str.Append(item.Name); //str.Append(","); //str.Append("\t"); //判斷屬性值 if (item.GetValue(obj, null) != null) { // 屬性值 str.Append(item.GetValue(obj, null)); } else { str.Append("空值"); } // 換行 if ((j+1) % 2 == 0) { str.Append("\n"); } // 輸出逗號 else if (j % 2 == 0) { str.Append(","); } j++; } } } HttpContext.Current.Response.Clear(); // 啟用緩衝 HttpContext.Current.Response.Buffer = true; //中文編碼 HttpContext.Current.Response.Charset = "GB2312"; // 或者 "utf-8" // 設定編碼方式 HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; //檔案名稱 string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".txt"; /// 設定http 要求標頭,直接指向檔案 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(filename)); //指定返回的是一個不能被用戶端讀取的流,必須被下載 HttpContext.Current.Response.ContentType = "text/plain"; // 或者 application/ms-txt //把檔案流發送到用戶端 HttpContext.Current.Response.Write(str.ToString()); // 停止頁面的執行 HttpContext.Current.Response.End(); }
因時間倉促,代碼 也有不足之處,如果您有什麼好的想法,歡迎提出並與我交流