C# 常用公共方法

2019-12-30 13:32:46刘景俊

C# 常用公共方法,具体内容如下

1.后台调用weburl


string hostUrl = "http://www.easck.com/pre>

2.检测输入URL是否合法


/// <summary>
 /// 判断网址是否可以访问
 /// </summary>
 /// <param name="Url"></param>
 /// <returns></returns>
 protected bool ChkPageUrl(string url)
 {
  bool result = false;
  try
  {
   HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
   myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
   myHttpWebRequest.Method = "GET";
   HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
   if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
   {
    result = true;
   }
   myHttpWebResponse.Close();
  }
  catch
  {
   result = false;
  }

  return result;
 }

3.批量导出


 /// <summary>
  /// 批量导出
  /// </summary>
  /// <returns></returns>
  public FileResult ExportStu()
  {
   //创建Excel文件的对象
   NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
   //添加一个sheet
   NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
   int pager_totalcount = (int)Session["pager_totalcount"];
   int totalCount = 0;
   //获取list数据
   List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount);

   //给sheet1添加第一行的头部标题
   NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
   //创建时间 名称 商户订单号 | 交易号 对方 金额(元) 状态
   row1.CreateCell(0).SetCellValue("编号");
   row1.CreateCell(1).SetCellValue("标题");
   row1.CreateCell(2).SetCellValue("内容");
   int Width = 256;
   sheet1.SetColumnWidth(0, 10 * Width);
   sheet1.SetColumnWidth(1, 25 * Width);
   sheet1.SetColumnWidth(2, 60 * Width);
   if (infoList != null)
   {
    var list = infoList.OrderByDescending(p => p.ID);

    if (list != null)
    {
     int i = 0;
     //将数据逐步写入sheet1各个行
     foreach (var item in list)
     {
      i = i + 1;
      NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
      rowtemp.CreateCell(0).SetCellValue(item.ID.ToString());
      rowtemp.CreateCell(1).SetCellValue(item.Title == null ? "" : item.Title.ToString());
      rowtemp.CreateCell(2).SetCellValue(item.Content == null ? "" : item.Content.ToString());
     }
    }
   }
   // 写入到客户端 
   System.IO.MemoryStream ms = new System.IO.MemoryStream();
   book.Write(ms);
   ms.Seek(0, System.IO.SeekOrigin.Begin);
   return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

  }