using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.IO; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Threading; using System.Runtime.Serialization; using System.Globalization; using System.Runtime.Serialization.Formatters.Binary; using System.Collections.Generic; namespace Demo { public class Common { #region 类型转换(默认值)和判断 /// <summary> /// 判断对象是否为Int32类型的数字 /// </summary> /// <param name="Expression"></param> /// <returns></returns> public static bool IsNumeric(object expression) { if (expression != null) { return IsNumeric(expression.ToString()); } return false; } /// <summary> /// 判断对象是否为Int32类型的数字 /// </summary> /// <param name="Expression"></param> /// <returns></returns> public static bool IsNumeric(string expression) { if (expression != null) { string str = expression; if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*{1}quot;)) { if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1')) { return true; } } } return false; } /// <summary> /// 是否为Double类型 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool IsDouble(object expression) { if (expression != null) { return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?{1}quot;); } return false; } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool StrToBool(object expression, bool defValue) { if (expression != null) { return StrToBool(expression, defValue); } return defValue; } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool StrToBool(string expression, bool defValue) { if (expression != null) { if (string.Compare(expression, "true", true) == 0) { return true; } else if (string.Compare(expression, "false", true) == 0) { return false; } } return defValue; } /// <summary> /// 将对象转换为Int32类型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int StrToInt(object expression, int defValue) { if (expression != null) { return StrToInt(expression.ToString(), defValue); } return defValue; } /// <summary> /// 将对象转换为Int32类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int StrToInt(string str, int defValue) { if (str == null) return defValue; if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*{1}quot;)) { if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1')) { return Convert.ToInt32(str); } } return defValue; } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float StrToFloat(object strValue, float defValue) { if ((strValue == null)) { return defValue; } return StrToFloat(strValue.ToString(), defValue); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float StrToFloat(string strValue, float defValue) { if ((strValue == null) || (strValue.Length > 10)) { return defValue; } float intValue = defValue; if (strValue != null) { bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?{1}quot;); if (IsFloat) { intValue = Convert.ToSingle(strValue); } } return intValue; } /// <summary> /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型 /// </summary> /// <param name="strNumber">要确认的字符串数组</param> /// <returns>是则返加true 不是则返回 false</returns> public static bool IsNumericArray(string[] strNumber) { if (strNumber == null) { return false; } if (strNumber.Length < 1) { return false; } foreach (string id in strNumber) { if (!IsNumeric(id)) { return false; } } return true; } #endregion #region 日期处理 /// <summary> /// 获取中文星期 /// </summary> /// <param name="sDate"></param> /// <returns></returns> public static string getWeek(DateTime sDate) { string rStr = ""; switch (sDate.DayOfWeek.ToString()) { case "Sunday": rStr = "星期日"; break; case "Monday": rStr = "星期一"; break; case "Tuesday": rStr = "星期二"; break; case "Wednesday": rStr = "星期三"; break; case "Thursday": rStr = "星期四"; break; case "Friday": rStr = "星期五"; break; case "Saturday": rStr = "星期六"; break; } return rStr; } #endregion #region 字符串处理 /// <summary> /// 统计单个字符car在str中出现的次数 /// </summary> /// <param name="str">原始字符串</param> /// <param name="car">要统计的字符</param> /// <returns></returns> public static int GetSubCharCount(string str, char car) { int i = 0; char[] charstr = str.ToCharArray(); for (int j = 0; j < charstr.Length; j++) { if (car == charstr[j]) { i++; } } return i; } /// <summary> /// 统计字符串sin在str中出现的次数 /// </summary> /// <param name="str">原始字符串</param> /// <param name="sin">要统计字符串</param> /// <returns></returns> public static int GetSubStringCount(string str, string sin) { int i = 0; int ibit = 0; while (true) { ibit = str.IndexOf(sin, ibit); if (ibit > 0) { ibit += sin.Length; i++; } else { break; } } return i; } /// <summary> /// 从字符串的指定位置截取指定长度的子字符串 /// </summary> /// <param name="str">原字符串</param> /// <param name="startIndex">子字符串的起始位置</param> /// <param name="length">子字符串的长度</param> /// <returns>子字符串</returns> public static string CutString(string str, int startIndex, int length) { if (startIndex >= 0) { if (length < 0) { length = length * -1; if (startIndex - length < 0) { length = startIndex; startIndex = 0; } else { startIndex = startIndex - length; } } if (startIndex > str.Length) { return ""; } } else { if (length < 0) { return ""; } else { if (length + startIndex > 0) { length = length + startIndex; startIndex = 0; } else { return ""; } } } if (str.Length - startIndex < length) { length = str.Length - startIndex; } return str.Substring(startIndex, length); } /// <summary> /// 从字符串的指定位置开始截取到字符串结尾的了符串 /// </summary> /// <param name="str">原字符串</param> /// <param name="startIndex">子字符串的起始位置</param> /// <returns>子字符串</returns> public static string CutString(string str, int startIndex) { return CutString(str, startIndex, str.Length); } /// <summary> /// 字符串如果操过指定长度则将超出的部分用指定字符串代替 /// </summary> /// <param name="p_SrcString">要检查的字符串</param> /// <param name="p_Length">指定长度</param> /// <param name="p_TailString">用于替换的字符串</param> /// <returns>截取后的字符串</returns> public static string GetSubString(string p_SrcString, int p_Length, string p_TailString) { return GetSubString(p_SrcString, 0, p_Length, p_TailString); } public static string GetUnicodeSubString(string str, int len, string p_TailString) { string result = string.Empty;// 最终返回的结果 int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度 int charLen = str.Length;// 把字符平等对待时的字符串长度 int byteCount = 0;// 记录读取进度 int pos = 0;// 记录截取位置 if (byteLen > len) { for (int i = 0; i < charLen; i++) { if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2 byteCount += 2; else// 按英文字符计算加1 byteCount += 1; if (byteCount > len)// 超出时只记下上一个有效位置 { pos = i; break; } else if (byteCount == len)// 记下当前位置 { pos = i + 1; break; } } if (pos >= 0) result = str.Substring(0, pos) + p_TailString; } else result = str; return result; } /// <summary> /// 取指定长度的字符串 /// </summary> /// <param name="p_SrcString">要检查的字符串</param> /// <param name="p_StartIndex">起始位置</param> /// <param name="p_Length">指定长度</param> /// <param name="p_TailString">用于替换的字符串</param> /// <returns>截取后的字符串</returns> public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString) { string myResult = p_SrcString; Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString); foreach (char c in Encoding.UTF8.GetChars(bComments)) { //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3) if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3')) { //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+")) //当截取的起始位置超出字段串长度时 if (p_StartIndex >= p_SrcString.Length) { return ""; } else { return p_SrcString.Substring(p_StartIndex, ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length); } } } if (p_Length >= 0) { byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString); //当字符串长度大于起始位置 if (bsSrcString.Length > p_StartIndex) { int p_EndIndex = bsSrcString.Length; //当要截取的长度在字符串的有效长度范围内 if (bsSrcString.Length > (p_StartIndex + p_Length)) { p_EndIndex = p_Length + p_StartIndex; } else { //当不在有效范围内时,只取到字符串的结尾 p_Length = bsSrcString.Length - p_StartIndex; p_TailString = ""; } int nRealLength = p_Length; int[] anResultFlag = new int[p_Length]; byte[] bsResult = null; int nFlag = 0; for (int i = p_StartIndex; i < p_EndIndex; i++) { if (bsSrcString[i] > 127) { nFlag++; if (nFlag == 3) { nFlag = 1; } } else { nFlag = 0; } anResultFlag[i] = nFlag; } if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1)) { nRealLength = p_Length + 1; } bsResult = new byte[nRealLength]; Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength); myResult = Encoding.Default.GetString(bsResult); myResult = myResult + p_TailString; } } return myResult; } /// <summary> /// 把object格式化成字符串 /// </summary> /// <param name="value">数据对象</param> /// <returns>格式化后字符串</returns> public static string ToString(object value) { if (value == null || value == DBNull.Value) return string.Empty; if (value is DateTime) return ToString(value, "yyyy-MM-dd"); if (value is Decimal) return ToString(value, "n2"); return value.ToString(); } public static DateTime ToDateTime(object value) { if (value == null || value == DBNull.Value) { return DateTime.MinValue; } else return Convert.ToDateTime(value); } public static int ToInt(object value) { if (value == null || value == DBNull.Value) { return 0; } else return Convert.ToInt32(value); } public static bool ToBool(object value) { if (value == null || value == DBNull.Value) { return false; } else return Convert.ToBoolean(value); } public static Decimal ToDecimal(object value) { if (value == null || value == DBNull.Value) { return 0m; } else return Convert.ToDecimal(value); } /// <summary> /// 把object格式化成字符串 /// </summary> /// <param name="value">数据对象</param> /// <param name="format">格式化引擎字符串</param> /// <returns>格式化后字符串</returns> public static string ToString(object value, string format) { if (value == null || value == DBNull.Value) return string.Empty; if (value is DateTime) return ((DateTime)value).ToString(format); if (value is Decimal) return ((Decimal)value).ToString(format); return value.ToString(); } /// <summary> /// 将byte[]转换为Image /// </summary> /// <param name="bytes">字节数组</param> /// <returns>Image</returns> public static Image ReadImage(byte[] bytes) { MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); BinaryFormatter bf = new BinaryFormatter(); object obj = bf.Deserialize(ms); ms.Close(); return (Image)obj; } /// <summary> /// 将Image转换为byte[] /// </summary> /// <param name="image">Image</param> /// <returns>byte[]</returns> public static byte[] ConvertImage(Image image) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, (object)image); ms.Close(); return ms.ToArray(); } #endregion #region 正则验证 自定义替换字符串函数(可不区分大小写 ) /// <summary> /// 正则验证 /// </summary> /// <param name="value">值</param> /// <param name="rex">正则表达式</param> /// <returns></returns> public static bool CheckRegEx(string value, string rex) { Regex regex = new Regex(rex, RegexOptions.Compiled); return regex.Match(value).Success; } /// <summary> /// 自定义替换字符串函数 /// </summary> /// <param name="SourceString">原始字符串</param> /// <param name="SearchString">要替换的字符串</param> /// <param name="ReplaceString">被替换的字符串</param> /// <param name="IsCaseInsensetive">是否区分大小写</param> /// <returns></returns> public static string RexReplace(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive) { return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None); } #endregion #region 字符串输出到客户端、字符串保存到服务端文件 /// <summary> /// 生成指定数量的html空格符号 /// </summary> public static string GetSpacesString(int spacesCount) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < spacesCount; i++) { sb.Append(" "); } return sb.ToString(); } /// <summary> /// 把 JavaScript 语句加上前缀后缀 /// </summary> /// <param name="script">JavaScript语句</param> /// <returns>加上前缀后缀的语句</returns> public static string GetScript(string script) { return "<script type=\"text/javascript\">" + script + "</script>"; } /// <summary> /// 把字符串转化成 JavaScript 中的字符串 /// </summary> /// <param name="value">原始串</param> /// <returns>JavaScript字符串</returns> public static string ToJSString(string value) { if (string.IsNullOrEmpty(value)) return string.Empty; // 处理 ( 反斜杠, 单引号, 双引号, 回车, 换行, 制表符 ) 转换成对应的16进制值 return value.Replace("\\", @"\x5C").Replace("'", @"\x27").Replace("\"", @"\x22").Replace("\r", @"\x0D").Replace("\n", @"\x0A").Replace("\t", @"\x09"); } /// <summary> /// 产生随机数目 /// </summary> /// <param name="length">随机数目长度</param> /// <returns>产生随机数目</returns> public static string GetRandomString(int length) { string ch = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; string ret = string.Empty; int intLength = ch.Length; Random rd = new Random(); for (int i = 0; i < length; i++) { ret += ch[rd.Next(intLength)]; } return ret; } /// <summary> /// 产生获得焦点 JavaScript 代码 /// </summary> /// <param name="id">控件ID</param> /// <returns>获得焦点代码</returns> public static string GetFocusScript(string id) { return string.Format("document.getElementById(\"{0}\").focus();document.getElementById(\"{0}\").value=document.getElementById(\"{0}\").value;", id); } /// <summary> /// 产生获得选中内容 JavaScript 代码 /// </summary> /// <param name="id">控件ID</param> /// <returns>获得选中内容代码</returns> public static string GetSelectScript(string id) { return string.Format("document.getElementById(\"{0}\").focus();document.getElementById(\"{0}\").select();", id); } /// <summary> /// 保存字符串内容到客户端文件 /// </summary> /// <param name="content">字符串内容</param> /// <param name="fileName">文件名</param> public static void SaveAsFile(string content, string fileName) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Charset = "utf-8"; Response.ContentType = "text/plain"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName)); Response.Write(content); Response.End(); } /// <summary> /// 保存字符串内容到服务端文件 /// </summary> /// <param name="content">字符串内容</param> /// <param name="filePath">文件路径</param> public static void SaveAsServerFile(string content, string filePath) { StreamWriter sr = new StreamWriter(filePath, false, System.Text.Encoding.Default); sr.Write(content); sr.Close(); } #endregion #region Cookie处理 /// <summary> /// 写cookie值 /// </summary> /// <param name="strName">名称</param> /// <param name="strValue">值</param> public static void WriteCookie(string strName, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie.Value = strValue; HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 写cookie值 /// </summary> /// <param name="strName">名称</param> /// <param name="key">索引</param> /// <param name="strValue">值</param> public static void WriteCookie(string strName, string key, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie[key] = strValue; HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 写cookie值 /// </summary> /// <param name="strName">名称</param> /// <param name="strValue">值</param> /// <param name="strValue">过期时间(分钟)</param> public static void WriteCookie(string strName, string strValue, int expires) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie.Value = strValue; cookie.Expires = DateTime.Now.AddMinutes(expires); HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 写cookie值 /// </summary> /// <param name="strName">名称</param> /// <param name="strValue">值</param> /// <param name="strValue">过期时间(分钟)</param> /// <param name="strValue">cookie存在的域范围</param> public static void WriteCookie(string strName, string strValue, int expires, string domain) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie.Value = strValue; cookie.Expires = DateTime.Now.AddMinutes(expires); cookie.Domain = domain; HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 读cookie值 /// </summary> /// <param name="strName">名称</param> /// <returns>cookie值</returns> public static string GetCookie(string strName) { if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null) { return HttpContext.Current.Request.Cookies[strName].Value.ToString(); } return ""; } /// <summary> /// 读cookie值 /// </summary> /// <param name="strName">名称</param> /// <returns>cookie值</returns> public static string GetCookie(string strName, string key) { if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null) { return HttpContext.Current.Request.Cookies[strName][key].ToString(); } return ""; } /// <summary> /// 删除Cookies /// </summary> /// <param name="strName">名称</param> /// <param name="domain">域名</param> /// <returns></returns> public static void DelCookie(string strName, string domain) { HttpCookie cookie = new HttpCookie(strName); WriteCookie(strName, "", -60, domain); } /// <summary> /// 删除Cookies /// </summary> /// <param name="strName">名称</param> /// <returns></returns> public static void DelCookie(string strName) { HttpCookie cookie = new HttpCookie(strName); WriteCookie(strName, "", -60); } #endregion #region 加密 解密 方法(DES/md5) //默认密钥向量 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; //private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F }; ///<summary> ///DES加密字符串 ///</summary> ///<param name="encryptString">待加密的字符串</param> ///<param name="encryptKey">加密密钥,要求为8位</param> ///<returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string Encode(string encryptString, string encryptKey) { encryptKey = Common.GetSubString(encryptKey, 8, ""); encryptKey = encryptKey.PadRight(8, ' '); byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } /// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string Decode(string decryptString, string decryptKey) { try { decryptKey = Common.GetSubString(decryptKey, 8, ""); decryptKey = decryptKey.PadRight(8, ' '); byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return ""; } } /// <summary> /// MD5加密 /// </summary> /// <param name="str">加密字符</param> /// <param name="code">加密位数16/32</param> /// <returns></returns> public static string md5(string str, int code) { string strEncrypt = string.Empty; if (code == 16) { strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16); } if (code == 32) { strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5"); } return strEncrypt; } /// <summary> /// MD5加密 /// </summary> /// <param name="str">原始字符串</param> /// <returns>MD5结果</returns> public static string md5(string str) { byte[] b = Encoding.Default.GetBytes(str); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } #endregion #region GridView DataSet、Control 导出到 Excel /// <summary> /// 导出 Excel 文件 /// </summary> /// <param name="ds">数据集</param> /// <param name="fileName">Excel 文件名(不含扩展名)</param> public static void ToExcel(DataSet ds, string fileName) { ToExcel(ds.Tables[0], fileName); } /// <summary> /// 导出 Excel 文件 /// </summary> /// <param name="ds">数据集</param> /// <param name="fileName">Excel 文件名(不含扩展名)</param> public static void ToExcel(DataTable dt, string fileName) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); GridView gv = new GridView(); gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound); gv.DataSource = dt; gv.DataBind(); gv.RenderControl(hw); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls"); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); Response.Write(tw.ToString()); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); gv.Dispose(); tw.Close(); tw.Flush(); } private static void gv_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { DataTable dt = (DataTable)(((GridView)sender).DataSource); if (e.Row.RowType == DataControlRowType.DataRow) { for (int i = 0; i < e.Row.Cells.Count; i++) { if (dt.Columns[i].DataType == typeof(string)) { e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } } } } /// <summary> /// 导出 Excel 文件 /// </summary> /// <param name="control">控件名称</param> /// <param name="fileName">Excel 文件名(不含扩展名)</param> public static void ToExcel(Control control, string fileName) { ToExcel(control, fileName, true); } /// <summary> /// 导出 Excel 文件 /// </summary> /// <param name="control">控件名称</param> /// <param name="fileName">Excel 文件名(不含扩展名)</param> /// <param name="unformat">是否去除链接格式化串</param> public static void ToExcel(Control control, string fileName, bool unformat) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); control.RenderControl(hw); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls"); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); string output = tw.ToString(); if (unformat) { // 用正则表达式去除HTML中的链接格式、图片格式 output = Regex.Replace(output, @"<\s*/?\s*a[^>]*>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase); output = Regex.Replace(output, @"<\s*/?\s*img[^>]*>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase); } Response.Write(output); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); } /// <summary> /// 导出生成的内容到excel /// </summary> /// <param name="titlename">标题</param> /// <param name="totolcontent">导出内容string</param> public static void ToExcel(string titlename, string totolcontent) { System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Charset = "gb2312"; //set the response mime type for excel System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(titlename) + ".xls"); //create a string writer System.IO.StringWriter tw = new System.IO.StringWriter(); //create an htmltextwriter which uses the stringwriter System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); hw.Write(totolcontent); System.Web.HttpContext.Current.Response.Write(tw.ToString()); System.Web.HttpContext.Current.Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); } #endregion #region 获取服务器 用户信息 和页面信息 /// <summary> /// 获取服务器IP /// </summary> public static string GetServerIp { get { return HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString(); } } /// <summary> /// 获取服务器操作系统 /// </summary> public static string GetServerOS { get { return Environment.OSVersion.VersionString; } } /// <summary> /// 获取服务器域名 /// </summary> public static string GetServerHost { get { return HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString(); } } /// <summary> /// 获取用户IP地址 /// </summary> /// <returns></returns> public static string GetIPAddress() { string result = String.Empty; result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(result)) { result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrEmpty(result)) { result = HttpContext.Current.Request.UserHostAddress; } if (string.IsNullOrEmpty(result)) { return "127.0.0.1"; } return result; } /// <summary> /// 获得当前完整Url地址 /// </summary> /// <returns>当前完整Url地址</returns> public static string GetScriptUrl() { return HttpContext.Current.Request.Url.ToString(); } /// <summary> /// 返回当前页面目录的url /// </summary> /// <param name="FileName">文件名</param> /// <returns></returns> public static string GetHomeBaseUrl(string FileName) { string Script_Name = Common.GetScriptUrl(); return string.Format("{0}/{1}", Script_Name.Remove(Script_Name.LastIndexOf("/")), FileName); } /// <summary> /// 返回上一个页面的地址 /// </summary> /// <returns>上一个页面的地址</returns> public static string GetUrlReferrer() { string retVal = null; try { retVal = HttpContext.Current.Request.UrlReferrer.ToString(); } catch { } if (retVal == null) return ""; return retVal; } /// <summary> /// 检测当前url是否包含指定的字符 /// </summary> /// <param name="sChar">要检测的字符</param> /// <returns></returns> public static bool CheckScriptNameChar(string sChar) { bool rBool = false; if (GetScriptUrl().ToLower().LastIndexOf(sChar) >= 0) rBool = true; return rBool; } /// <summary> /// 获取当前页面的扩展名 /// </summary> public static string GetScriptNameExt { get { return GetScriptUrl().Substring(GetScriptUrl().LastIndexOf(".") + 1); } } /// <summary> /// 获取当前访问页面地址参数 /// </summary> public static string GetScriptNameQueryString { get { return HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString(); } } ///// <summary> ///// 根据Url获得源文件内容 ///// </summary> ///// <param name="url">合法的Url地址</param> ///// <returns></returns> //public static string GetSourceTextByUrl(string url) //{ // WebRequest request = WebRequest.Create(url); // request.Timeout = 20000;//20秒超时 // WebResponse response = request.GetResponse(); // Stream resStream = response.GetResponseStream(); // StreamReader sr = new StreamReader(resStream); // return sr.ReadToEnd(); //} #endregion #region 文件下载 /// <summary> /// 文件直接下载 /// </summary> /// <param name="filePath">文件路径</param> /// <param name="filename">文件名称</param> public static void FileDownload(string filePath, string filename) { FileStream fileStream = new FileStream(HttpContext.Current.Server.MapPath(filePath), FileMode.Open); long fileSize = fileStream.Length; HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";"); HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString()); byte[] fileBuffer = new byte[fileSize]; fileStream.Read(fileBuffer, 0, (int)fileSize); HttpContext.Current.Response.BinaryWrite(fileBuffer); HttpContext.Current.Response.End(); } #endregion #region 将HTML代码格式化成文本框中输入的文字格式 /// <summary> /// 将HTML代码格式化成文本框中输入的文字格式 /// </summary> /// <param name="Input"></param> /// <returns></returns> public static String ToHtml(string Input) { StringBuilder sb = new StringBuilder(Input); sb.Replace("&", "&"); sb.Replace("<", "<"); sb.Replace(">", ">"); sb.Replace("\r\n", "<br />"); sb.Replace("\n", "<br />"); sb.Replace("\t", " "); sb.Replace("'", "'"); //sb.Replace(" ", " "); return sb.ToString(); } /// <summary> ///转换空格符、换行符为HTML字符 /// </summary> /// <param name="strContent">需要转换的字符</param> /// <returns></returns> public static string StrToHtml(string strContent) { strContent = strContent.Replace("\r\n", "<br />"); strContent = strContent.Replace("\n", "<br />"); strContent = strContent.Replace(@"\s", " "); return strContent; } #endregion #region 对网站图片是否存在进行处理 /// <summary> /// 验证图片是否存在 /// </summary> /// <param name="relpath"></param> /// <returns></returns> public static string validHasPic(string relpath) { string rev = relpath; if (string.IsNullOrEmpty(relpath)) { rev = "/Images/pic_no_124_94.jpg"; } return rev; } #endregion #region 序列化和反序列化方法(用于短消息功能) public static byte[] SerializeBuffer(MessageInfo msginfo) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, msginfo); byte[] buffer = ms.ToArray(); return buffer; } public static byte[] SerializeBuffer(DataSet ds) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ds); byte[] buffer = ms.ToArray(); return buffer; } public static byte[] SerializeBuffer(DataTable dt) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, dt); byte[] buffer = ms.ToArray(); return buffer; } public static byte[] SerializeBuffer(ComplaintMsg msginfo) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, msginfo); byte[] buffer = ms.ToArray(); return buffer; } /// <summary> /// 反序列化为DataSet /// </summary> /// <param name="buffer">字节数组(由dataset序列化得到)</param> /// <returns>dataset</returns> public static DataSet DeserializeDataSet(byte[] buffer) { BinaryFormatter bf = new BinaryFormatter(); DataSet ds = bf.Deserialize(new MemoryStream(buffer)) as DataSet; return ds; } /// <summary> /// 反序列化为MessageInfo /// </summary> /// <param name="buffer">字节数组(由MessageInfo序列化得到)</param> /// <returns>MessageInfo</returns> public static MessageInfo DeserializeModel(byte[] buffer) { BinaryFormatter bf = new BinaryFormatter(); MessageInfo messageInfo = bf.Deserialize(new MemoryStream(buffer)) as MessageInfo; return messageInfo; } /// <summary> /// 反序列化为ComplaintInfo /// </summary> /// <param name="buffer">字节数组(由MessageInfo序列化得到)</param> /// <returns>MessageInfo</returns> public static ComplaintMsg DeserializeComplaintInfo(byte[] buffer) { BinaryFormatter bf = new BinaryFormatter(); ComplaintMsg messageInfo = bf.Deserialize(new MemoryStream(buffer)) as ComplaintMsg; return messageInfo; } /// <summary> /// 反序列化为DataTable /// </summary> /// <param name="buffer">字节数组(由DataTable序列化得到)</param> /// <returns>DataTable</returns> public static DataTable DeserializeDatTable(byte[] buffer) { BinaryFormatter bf = new BinaryFormatter(); if (buffer != null) { DataTable dt = bf.Deserialize(new MemoryStream(buffer)) as DataTable; return dt; } else return new DataTable(); } #endregion #region 全角半角转换常量 /**/ /*最大的有效全角英文字符转换成int型数据的值*/ private const int MaxSBCcaseToInt = 65374; /**/ /*最小的有效全角英文字符转换成int型数据的值*/ private const int MinSBCcaseToInt = 65281; /**/ /*最大的有效半角英文字符转换成int型数据的值*/ private const int MaxDBCcaseToInt = 126; /**/ /*最小的有效半角英文字符转换成int型数据的值*/ private const int MinDBCcaseToInt = 33; /**/ /*对应的全角和半角的差*/ private const int Margin = 65248; #endregion #region 全角转换为半角 /// <summary> /// 全角转换为半角 /// </summary> /// <param name="originalStr">要进行全角到半角转换的字符串</param> /// <param name="start">要进行全角到半角转换的开始位置,不能大于end</param> /// <param name="end">要进行全角到半角转换的结束位置,不能小于start</param> /// <returns>转换成对应半角的字符串</returns> public static string ConvertSBCcaseToDBCcase(string originalStr, int start, int end) { #region 异常判断 if (start < 0 || end < 0) { throw new Exception("开始位置或结束位置不能小于零"); } if (start > end) { throw new Exception("开始位置不能大于结束位置"); } if (start >= originalStr.Length || end >= originalStr.Length) { throw new Exception("开始位置或结束位置必须小于字符串的最大长度"); } #endregion /**/ /*空字符串返回空*/ if (originalStr == "") { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < originalStr.Length; i++) { if (i >= start && i <= end) { sb.Append(ConvertSBCcaseToDBCcase(originalStr[i])); } else { sb.Append(originalStr[i]); } } return sb.ToString(); } #endregion #region 全角转换为半角 /// <summary> /// 全角转换为半角 /// </summary> /// <param name="originalStr">要进行全角到半角转换的字符串</param> /// <returns>转换成对应半角的字符串</returns> public static string ConvertSBCcaseToDBCcase(string originalStr) { return ConvertSBCcaseToDBCcase(originalStr, 0, originalStr.Length - 1); } #endregion #region 字符全角转换为半角 /// <summary> /// 字符全角转换为半角 /// </summary> /// <param name="originalChar">要进行全角到半角转换的字符</param> /// <returns>全角字符转换为半角后的字符</returns> public static char ConvertSBCcaseToDBCcase(char originalChar) { /**/ /*空格是特殊的,其全角和半角的差值也与其他字符不同*/ if ((int)originalChar == (int)' ') { return ' '; } else { if ((int)originalChar >= MinSBCcaseToInt && (int)originalChar <= MaxSBCcaseToInt) { return (char)(originalChar - Margin); } else { return originalChar; } } } #endregion #region 字符串半角转换为全角 /// <summary> /// 字符串半角转换为全角 /// </summary> /// <param name="originalStr">要进行半角到全角转换的字符串</param> /// <param name="start">要进行半角到全角转换的开始位置,不能大于end</param> /// <param name="end">要进行半角到全角转换的结束位置,不能小于start</param> /// <returns>转换成对应全角的字符串</returns> public static string ConvertDBCcaseToSBCcase(string originalStr, int start, int end) { #region "异常判断" if (start < 0 || end < 0) { throw new Exception("开始位置或结束位置不能小于零"); } if (start > end) { throw new Exception("开始位置不能大于结束位置"); } if (start >= originalStr.Length || end >= originalStr.Length) { throw new Exception("开始位置或结束位置必须小于字符串的最大长度"); } #endregion /**/ /*空字符串返回空*/ if (originalStr == "") { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < originalStr.Length; i++) { if (i >= start && i <= end) { sb.Append(ConvertDBCcaseToSBCcase(originalStr[i])); } else { sb.Append(originalStr[i]); } } return sb.ToString(); } #endregion #region 字符串半角转换为全角 /// <summary> /// 字符串半角转换为全角 /// </summary> /// <param name="originalStr">要进行半角到全角转换的字符串</param> /// <returns>转换成对应全角的字符串</returns> public static string ConvertDBCcaseToSBCcase(string originalStr) { return ConvertDBCcaseToSBCcase(originalStr, 0, originalStr.Length - 1); } #endregion #region 字符半角转换为全角 /// <summary> /// 字符半角转换为全角 /// </summary> /// <param name="originalChar">要进行半角到全角转换的字符</param> /// <returns>半角字符转换为全角后的字符</returns> public static char ConvertDBCcaseToSBCcase(char originalChar) { /**/ /*空格是特殊的,其全角和半角的差值也与其他字符不同*/ if ((int)originalChar == (int)' ') { return ' '; } else { if ((int)originalChar >= MinDBCcaseToInt && (int)originalChar <= MaxDBCcaseToInt) { return (char)(originalChar + Margin); } else { return originalChar; } } } #endregion #region 过滤HTML public static string NoHTML(string Htmlstring) { //删除脚本 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); //删除HTML Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, "<.+?>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, "<IMG.*?>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); Htmlstring.Replace("<", ""); Htmlstring.Replace(">", ""); Htmlstring.Replace("\r\n", ""); //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim(); return Htmlstring; } /// <summary> /// 把所有的HTML标签替换成空格 /// </summary> /// <param name="strHtml">要替换的HTML</param> /// <returns></returns> public static string ReplaceHtml(string strHtml) { strHtml = Regex.Replace(strHtml, "<.+?>","", RegexOptions.IgnoreCase); return strHtml; } public static string StripHTML(string strHtml) { string[] aryReg = { @"<script[^>]*?>.*?</script>", @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[", @"'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+", @"&(quot|#34);", @"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);", @"&(pound|#163);", @"&(copy|#169);", @"&#(\d+);", @"-->", @"<!--.*\n" }; string[] aryRep = { "", "", "", "\"", "&", "<", ">", " ", "\xa1", //chr(161), "\xa2", //chr(162), "\xa3", //chr(163), "\xa9", //chr(169), "", "\r\n", "" }; string newReg = aryReg[0]; string strOutput = strHtml; for (int i = 0; i < aryReg.Length; i++) { Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase); strOutput = regex.Replace(strOutput, aryRep[i]); } strOutput.Replace("<", ""); strOutput.Replace(">", ""); strOutput.Replace("\r\n", ""); return strOutput; } /// <summary> /// 移除HTML标签 /// </summary> /// <param name="HTMLStr">HTMLStr</param> public static string ParseTags(string HTMLStr) { return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); } /// <summary> /// 取出文本中的图片地址 /// </summary> /// <param name="HTMLStr">HTMLStr</param> public static string GetImgUrl(string HTMLStr) { string str = string.Empty; string sPattern = @"^<img\s+[^>]*>"; Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>", RegexOptions.Compiled); Match m = r.Match(HTMLStr.ToLower()); if (m.Success) str = m.Result("${url}"); return str; } #endregion #region 农历日期 /// <summary> /// 返回格式化的公历显示 /// </summary> /// <returns>格式如:2008年05月14日</returns> public static string GetDate() { //int y = m_Date.Year; int m = DateTime.Today.Month; int d = DateTime.Today.Day; return String.Format("{0:00}月{1:00}日", m, d); } /// <summary> /// 返回格式化的星期显示 /// </summary> /// <returns>格式如:星期日</returns> public static string GetWeek() { string ws = "星期"; int w = Convert.ToInt32(DateTime.Today.DayOfWeek); ws = ws + "日一二三四五六".Substring(w, 1); return ws; } /// <summary> /// 返回格式化的农历显示 /// </summary> /// <returns>格式如:戊子(鼠)年润四月廿三</returns> public static string GetCNDate() { DateTime m_Date = DateTime.Today;//今天的日期 ChineseLunisolarCalendar cnCalendar = new ChineseLunisolarCalendar(); int cny = cnCalendar.GetSexagenaryYear(m_Date);//农历的年月日 int cnm = cnCalendar.GetMonth(m_Date);//农历的年月日 int cnd = cnCalendar.GetDayOfMonth(m_Date);//农历的年月日 int icnm = cnCalendar.GetLeapMonth(cnCalendar.GetYear(m_Date));//农历闰月 string txcns = ""; const string szText1 = "癸甲乙丙丁戊己庚辛壬"; const string szText2 = "亥子丑寅卯辰巳午未申酉戌"; const string szText3 = "猪鼠牛虎免龙蛇马羊猴鸡狗"; int tn = cny % 10; //天干 int dn = cny % 12; //地支 txcns += szText1.Substring(tn, 1); txcns += szText2.Substring(dn, 1); txcns += "(" + szText3.Substring(dn, 1) + ")年 | "; //格式化月份显示 string[] cnMonth ={ "", "正月", "二月", "三月", "四月", "五月", "六月" , "七月", "八月", "九月", "十月", "十一月", "十二月", "十二月" }; if (icnm > 0) { for (int i = icnm + 1; i < 13; i++) cnMonth[i] = cnMonth[i - 1]; cnMonth[icnm] = "闰" + cnMonth[icnm]; } txcns += cnMonth[cnm]; string[] cnDay ={ "", "初一", "初二", "初三", "初四", "初五", "初六", "初七" , "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六" , "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五" , "廿六", "廿七", "廿八", "廿九", "三十" }; txcns += cnDay[cnd]; return txcns; } #endregion public static string CreateJsonByDataTable(DataTable dt) { StringBuilder jsonString = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { jsonString.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { jsonString.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { if (j < dt.Columns.Count - 1) { jsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\","); } else if (j == dt.Columns.Count - 1) { jsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\""); } } if (i == dt.Rows.Count - 1) { jsonString.Append("}"); } else { jsonString.Append("},"); } } jsonString.Append("]"); return jsonString.ToString(); } else { return string.Empty; } } } }