c# 开发工具类
stemp0 快速開發(fā),需要使用很多小函數,方便快捷,保留適合自己的方法,會使開發(fā)效率提升
cache 緩存輔助類
using System; using System.Collections.Generic; using System.Linq; using System.Web;namespace mofa.commom {//cache幫助類public class Cache{/// <summary>/// 設定絕對的過期時間(超過多少天后過期,單位是天)/// </summary>/// <param name="CacheKey"></param>/// <param name="objObject"></param>/// <param name="seconds">超過多少天后過期,單位是天</param>public static void SetCacheDateTime(string CacheKey, object objObject, long days){System.Web.Caching.Cache objCache = HttpRuntime.Cache;//objCache.Insert(CacheKey, objObject, null, DateTime.UtcNow.AddDays(days), TimeSpan.Zero);objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddDays(days), System.Web.Caching.Cache.NoSlidingExpiration);}/// <summary>/// /// <param name="CacheKey"></param>/// <param name="objObject"></param>/// <param name="seconds">超過多少天后過期,單位是天</param>public static TEntity GetCacheDateTime<TEntity>(string CacheKey) where TEntity:class{System.Web.Caching.Cache objCache = HttpRuntime.Cache;return objCache.Get(CacheKey) as TEntity;}/// <summary>/// 設置當前應用程序指定包含相對過期時間Cache值(超過多少天不調用就失效,單位是天)/// </summary>/// <param name="CacheKey"></param>/// <param name="objObject"></param>/// <param name="timeSpan">超過多少天不調用就失效,單位是天</param>public static void SetCacheTimeSpan(string CacheKey, object objObject, long days){System.Web.Caching.Cache objCache = HttpRuntime.Cache;objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, TimeSpan.FromDays(days));}} } View Codeexcel 輔助類
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web;namespace mofa.commom {using NPOI;using NPOI.HPSF;using NPOI.HSSF;using NPOI.HSSF.UserModel;using NPOI.POIFS;using NPOI.SS.UserModel;using NPOI.SS.Util;using NPOI.Util;using System.Data;public class ExcelHelper{/// <summary>/// 創(chuàng)建工作簿/// </summary>/// <param name="fileName">下載文件名</param>/// <param name="dt">數據源</param>public string CreateSheet(DataTable dt){string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}FolderDeal(HttpContext.Current.Server.MapPath(DataFile));StringBuilder builder = new StringBuilder();string name = System.DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + ".xls";string fileName = filepath + name;//創(chuàng)建工作薄 IWorkbook workbook = new HSSFWorkbook(); ;//string extension = System.IO.Path.GetExtension(fileName);//HSSFWorkbook workbook = new HSSFWorkbook();//Stream ms = new MemoryStream();//創(chuàng)建一個名稱為Payment的工作表ISheet paymentSheet = workbook.CreateSheet("Payment");//數據源DataTable tbPayment = dt;//頭部標題IRow paymentHeaderRow = paymentSheet.CreateRow(0);//循環(huán)添加標題foreach (DataColumn column in tbPayment.Columns){paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);//paymentHeaderRow.Height = (short)3000; }ICellStyle style = workbook.CreateCellStyle();//樣式style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;// 內容int paymentRowIndex = 1;foreach (DataRow row in tbPayment.Rows){IRow newRow = paymentSheet.CreateRow(paymentRowIndex);//循環(huán)添加列的對應內容foreach (DataColumn column in tbPayment.Columns){newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());}newRow.RowStyle = style;paymentRowIndex++;}//列寬自適應,只對英文和數字有效for (int i = 0; i <= dt.Rows.Count; i++){paymentSheet.AutoSizeColumn(i);}//獲取當前列的寬度,然后對比本列的長度,取最大值for (int columnNum = 0; columnNum <= dt.Columns.Count; columnNum++){int columnWidth = paymentSheet.GetColumnWidth(columnNum) / 256;for (int rowNum = 1; rowNum <= paymentSheet.LastRowNum; rowNum++){IRow currentRow;//當前行未被使用過if (paymentSheet.GetRow(rowNum) == null){currentRow = paymentSheet.CreateRow(rowNum);}else{currentRow = paymentSheet.GetRow(rowNum);}if (currentRow.GetCell(columnNum) != null){ICell currentCell = currentRow.GetCell(columnNum);int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;if (columnWidth < length){columnWidth = length;}}}paymentSheet.SetColumnWidth(columnNum, columnWidth * 256);}//將表內容寫入流 通知瀏覽器下載//workbook.Write(ms);//System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName));//System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //進行二進制流下在try{FileStream fs = File.OpenWrite(fileName);workbook.Write(fs);//向打開的這個Excel文件中寫入表單并保存。 fs.Close();fs.Dispose();}catch (Exception ex){throw new Exception(ex.Message);}workbook = null;//ms.Close();//ms.Dispose();return DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "/" + name;}private void FolderDeal(string folderFullName){//throw new NotImplementedException();DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);if (TheFolder.GetDirectories().Count() > 1){foreach (DirectoryInfo item in TheFolder.GetDirectories()){DateTime now = DateTime.Now;if (item.Name != now.ToStringByDatetime(DateTimeType.yyyyMMdd) && item.Name != now.AddDays(-1).ToStringByDatetime(DateTimeType.yyyyMMdd)){item.Delete(true);}}}}public string CreateSheet(DataTable dt, string fName, bool isSpan = false){string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}FolderDeal(HttpContext.Current.Server.MapPath(DataFile));StringBuilder builder = new StringBuilder();string name = fName + System.DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + ".xls";string fileName = filepath + name;//創(chuàng)建工作薄 IWorkbook workbook = new HSSFWorkbook(); ;//string extension = System.IO.Path.GetExtension(fileName);//HSSFWorkbook workbook = new HSSFWorkbook();//Stream ms = new MemoryStream();//創(chuàng)建一個名稱為Payment的工作表ISheet paymentSheet = workbook.CreateSheet("Payment");//數據源DataTable tbPayment = dt;//頭部標題IRow paymentHeaderRow = paymentSheet.CreateRow(0);//循環(huán)添加標題foreach (DataColumn column in tbPayment.Columns){paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);//paymentHeaderRow.Height = (short)3000; }ICellStyle style = workbook.CreateCellStyle();//樣式style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;// 內容int paymentRowIndex = 1;foreach (DataRow row in tbPayment.Rows){IRow newRow = paymentSheet.CreateRow(paymentRowIndex);//循環(huán)添加列的對應內容foreach (DataColumn column in tbPayment.Columns){newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());}newRow.RowStyle = style;paymentRowIndex++;}//列寬自適應,只對英文和數字有效for (int i = 0; i <= dt.Rows.Count; i++){paymentSheet.AutoSizeColumn(i);}//獲取當前列的寬度,然后對比本列的長度,取最大值for (int columnNum = 0; columnNum <= dt.Columns.Count; columnNum++){int columnWidth = paymentSheet.GetColumnWidth(columnNum) / 256;for (int rowNum = 1; rowNum <= paymentSheet.LastRowNum; rowNum++){IRow currentRow;//當前行未被使用過if (paymentSheet.GetRow(rowNum) == null){currentRow = paymentSheet.CreateRow(rowNum);}else{currentRow = paymentSheet.GetRow(rowNum);}if (currentRow.GetCell(columnNum) != null){ICell currentCell = currentRow.GetCell(columnNum);int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;if (columnWidth < length){columnWidth = length;}}}paymentSheet.SetColumnWidth(columnNum, columnWidth * 256);}//將表內容寫入流 通知瀏覽器下載//workbook.Write(ms);//System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName));//System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //進行二進制流下在try{FileStream fs = File.OpenWrite(fileName);workbook.Write(fs);//向打開的這個Excel文件中寫入表單并保存。 fs.Close();fs.Dispose();}catch (Exception ex){throw new Exception(ex.Message);}workbook = null;//ms.Close();//ms.Dispose();return DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "/" + name;}public string CreateDetailSheet(DataTable dt, string fName){string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}FolderDeal(HttpContext.Current.Server.MapPath(DataFile));StringBuilder builder = new StringBuilder();string name = fName + System.DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + ".xls";string fileName = filepath + name;//創(chuàng)建工作薄 IWorkbook workbook = new HSSFWorkbook(); ;//創(chuàng)建一個名稱為Payment的工作表ISheet paymentSheet = workbook.CreateSheet("Payment");//數據源DataTable tbPayment = dt;//頭部標題IRow paymentHeaderRow = paymentSheet.CreateRow(0);//循環(huán)添加標題foreach (DataColumn column in tbPayment.Columns){paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);//paymentHeaderRow.Height = (short)3000; }ICellStyle style = workbook.CreateCellStyle();//樣式style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;// 內容int paymentRowIndex = 1;//foreach (DataRow row in tbPayment.Rows)//{// IRow newRow = paymentSheet.CreateRow(paymentRowIndex);// //循環(huán)添加列的對應內容// foreach (DataColumn column in tbPayment.Columns)// {// newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());// }// newRow.RowStyle = style;// paymentRowIndex++;//}string tid = tbPayment.Rows.Count > 0 ? tbPayment.Rows[0]["訂單編號"].ToString() : "";string oid = tbPayment.Rows.Count > 0 ? tbPayment.Rows[0]["訂單ID"].ToString() : "";int tspan = 0;int ospan = 0;for (int i = 0; i < tbPayment.Rows.Count; i++){IRow newRow = paymentSheet.CreateRow(paymentRowIndex);//循環(huán)添加列的對應內容foreach (DataColumn column in tbPayment.Columns){newRow.CreateCell(column.Ordinal).SetCellValue(tbPayment.Rows[i][column].ToString());}if (i > 0){if (tid == tbPayment.Rows[i]["訂單編號"].ToString()){tspan++;for (int j = 0; j < 6; j++){//設置一個合并單元格區(qū)域,使用上下左右定義CellRangeAddress區(qū)域//CellRangeAddress四個參數為:起始行,結束行,起始列,結束列paymentSheet.AddMergedRegion(new CellRangeAddress(i - tspan + 1, i + 1, j, j));}}else{tid = tbPayment.Rows[i]["訂單編號"].ToString();tspan = 0;}if (oid == tbPayment.Rows[i]["訂單ID"].ToString()){ospan++;for (int k = 6; k < 19; k++){paymentSheet.AddMergedRegion(new CellRangeAddress(i - ospan + 1, i + 1, k, k));}}else{oid = tbPayment.Rows[i]["訂單ID"].ToString();ospan = 0;}}newRow.RowStyle = style;paymentRowIndex++;}//列寬自適應,只對英文和數字有效for (int i = 0; i <= dt.Rows.Count; i++){paymentSheet.AutoSizeColumn(i);}//獲取當前列的寬度,然后對比本列的長度,取最大值for (int columnNum = 0; columnNum <= dt.Columns.Count; columnNum++){int columnWidth = paymentSheet.GetColumnWidth(columnNum) / 256;for (int rowNum = 1; rowNum <= paymentSheet.LastRowNum; rowNum++){IRow currentRow;//當前行未被使用過if (paymentSheet.GetRow(rowNum) == null){currentRow = paymentSheet.CreateRow(rowNum);}else{currentRow = paymentSheet.GetRow(rowNum);}if (currentRow.GetCell(columnNum) != null){ICell currentCell = currentRow.GetCell(columnNum);int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;if (columnWidth < length){columnWidth = length;}}}paymentSheet.SetColumnWidth(columnNum, columnWidth * 256);}try{FileStream fs = File.OpenWrite(fileName);workbook.Write(fs);//向打開的這個Excel文件中寫入表單并保存。 fs.Close();fs.Dispose();}catch (Exception ex){throw new Exception(ex.Message);}workbook = null;return DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "/" + name;}#region 導出排班Excel報表public string DeriveExcel(System.Data.DataTable table, string shopname, string yearmonth){string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}FolderDeal(HttpContext.Current.Server.MapPath(DataFile));FileInfo f = null;try{//獲取年,月int year = Convert.ToInt32(yearmonth.Substring(0, 4));int month = Convert.ToInt32(yearmonth.Substring(4));//獲取當前月天數int days = DateTime.DaysInMonth(year, month);//行號,疊加int rowNum = 0;HSSFWorkbook workbook = new HSSFWorkbook();//合并單元格CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, days + 2);//創(chuàng)建表var sheet = workbook.CreateSheet(string.Format("{0}{1}月份排班表", shopname, month));//首行樣式ICellStyle style = workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.CENTER;NPOI.SS.UserModel.IFont font = workbook.CreateFont();font.FontHeightInPoints = (short)20;style.SetFont(font);IRow row = sheet.CreateRow(rowNum++);ICell cell = row.CreateCell(0);sheet.AddMergedRegion(cellRangeAddress);cell.CellStyle = style;cell.SetCellValue(string.Format("{0}{1}月份排班表", shopname, month));//添加次類型行ICellStyle timeTypeStyle = workbook.CreateCellStyle();timeTypeStyle.Alignment = HorizontalAlignment.CENTER;NPOI.SS.UserModel.IFont font2 = workbook.CreateFont();font2.FontHeightInPoints = (short)12;timeTypeStyle.SetFont(font2);CellRangeAddress cellRangeAddress2 = new CellRangeAddress(1, 1, 0, days + 2);sheet.AddMergedRegion(cellRangeAddress2);row = sheet.CreateRow(rowNum++);cell = row.CreateCell(0);cell.CellStyle = timeTypeStyle;cell.SetCellValue("{信息}");//日期行ICellStyle style2 = workbook.CreateCellStyle();style2.Alignment = HorizontalAlignment.CENTER;style2.VerticalAlignment = VerticalAlignment.CENTER;row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue("用戶名");for (int j = 1; j <= days; j++){cell = row.CreateCell(j);cell.CellStyle = style2;cell.SetCellValue(j);}cell = row.CreateCell(days + 1);cell.CellStyle = style2;cell.SetCellValue("合計");cell = row.CreateCell(days + 2);cell.CellStyle = style2;cell.SetCellValue("備注");//星期行//紅色居中樣式ICellStyle style3 = workbook.CreateCellStyle();style3.Alignment = HorizontalAlignment.CENTER;style3.VerticalAlignment = VerticalAlignment.CENTER;NPOI.SS.UserModel.IFont font3 = workbook.CreateFont();font3.Color = (short)FontColor.RED;style3.SetFont(font3);row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue("星期");string[] Day = new string[] { "日", "一", "二", "三", "四", "五", "六" };int workDay = 0;for (int i = 1; i <= days; i++){DateTime time = Convert.ToDateTime(year.ToString() + "-" + month.ToString() + "-" + i.ToString());string week = Day[Convert.ToInt32(time.DayOfWeek.ToString("d"))].ToString();cell = row.CreateCell(i);if (week == "六" || week == "日"){cell.CellStyle = style3;}else{cell.CellStyle = style2;}//合計工作日if (week != "六" && week != "日"){workDay++;}cell.SetCellValue(week);}cell = row.CreateCell(days + 1);cell.CellStyle = style2;cell.SetCellValue("班:" + workDay + " 休:" + (days - workDay));cell = row.CreateCell(days + 2);cell.SetCellValue("");//添加數據庫信息foreach (DataRow item in table.Rows){//名字row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue(item["Name"].ToString());//信息for (int i = 1; i <= days; i++){cell = row.CreateCell(i);cell.CellStyle = style2;cell.SetCellValue(item["day" + i.ToString()].ToString());}//合計,備注cell = row.CreateCell(days + 1);cell.CellStyle = style2;cell.SetCellValue(item["ActualDay"].ToString() == "Empty" ? "" : item["ActualDay"].ToString());cell = row.CreateCell(days + 2);cell.CellStyle = style2;cell.SetCellValue(item["remark"].ToString() == "Empty" ? "" : item["remark"].ToString());}CellRangeAddress cellRangeAddress3 = new CellRangeAddress(rowNum, rowNum, 0, days + 2);sheet.AddMergedRegion(cellRangeAddress3);row = sheet.CreateRow(rowNum++);cell = row.CreateCell(0);cell.CellStyle = style3;cell.SetCellValue("備注:。");int fileNum = 1;string filename = string.Format("{0}{1}年{2}月份信息.xls", shopname, year, month);f = new FileInfo(filepath + filename);while (f.Exists){filename = string.Format("{0}{1}年{2}月份信息({3}).xls", shopname, year, month, fileNum++);f = new FileInfo(filepath + filename);}using (var fs = f.OpenWrite()){workbook.Write(fs); //向打開的這個xls文件中寫入Sheet表并保存。 }return filename;}catch (Exception){throw;}}#endregion#region 導出排班Excel報表模板public string DeriveExcelModel(System.Data.DataTable table, string shopname, string yearmonth){string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}FolderDeal(HttpContext.Current.Server.MapPath(DataFile));FileInfo f = null;try{//獲取年,月int year = Convert.ToInt32(yearmonth.Substring(0, 4));int month = Convert.ToInt32(yearmonth.Substring(4));//獲取當前月天數int days = DateTime.DaysInMonth(year, month);//行號,疊加int rowNum = 0;HSSFWorkbook workbook = new HSSFWorkbook();//合并單元格CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, days + 6);//創(chuàng)建表var sheet = workbook.CreateSheet(string.Format("{0}{1}月份排班表", shopname, month));//首行樣式ICellStyle style = workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.CENTER;NPOI.SS.UserModel.IFont font = workbook.CreateFont();font.FontHeightInPoints = (short)20;style.SetFont(font);IRow row = sheet.CreateRow(rowNum++);ICell cell = row.CreateCell(0);sheet.AddMergedRegion(cellRangeAddress);cell.CellStyle = style;cell.SetCellValue(string.Format("{0}{1}月份排班表", shopname, month));//添加類型行ICellStyle timeTypeStyle = workbook.CreateCellStyle();timeTypeStyle.Alignment = HorizontalAlignment.CENTER;NPOI.SS.UserModel.IFont font2 = workbook.CreateFont();font2.FontHeightInPoints = (short)12;timeTypeStyle.SetFont(font2);CellRangeAddress cellRangeAddress2 = new CellRangeAddress(1, 1, 0, days + 6);sheet.AddMergedRegion(cellRangeAddress2);row = sheet.CreateRow(rowNum++);cell = row.CreateCell(0);cell.CellStyle = timeTypeStyle;cell.SetCellValue("{息}");//日期行ICellStyle style2 = workbook.CreateCellStyle();style2.Alignment = HorizontalAlignment.CENTER;style2.VerticalAlignment = VerticalAlignment.CENTER;row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue(shopname);cell = row.CreateCell(1);cell.CellStyle = style2;cell.SetCellValue(yearmonth);for (int j = 1; j <= days; j++){cell = row.CreateCell(j + 1);cell.CellStyle = style2;cell.SetCellValue(j + "號");}cell = row.CreateCell(days + 2);cell.CellStyle = style2;cell.SetCellValue("分");cell = row.CreateCell(days + 3);cell.CellStyle = style2;cell.SetCellValue("天");cell = row.CreateCell(days + 4);cell.CellStyle = style2;cell.SetCellValue("天");cell = row.CreateCell(days + 5);cell.CellStyle = style2;cell.SetCellValue("車費補貼");cell = row.CreateCell(days + 6);cell.CellStyle = style2;cell.SetCellValue("備注");//星期行//紅色居中樣式ICellStyle style3 = workbook.CreateCellStyle();style3.Alignment = HorizontalAlignment.CENTER;style3.VerticalAlignment = VerticalAlignment.CENTER;NPOI.SS.UserModel.IFont font3 = workbook.CreateFont();font3.Color = (short)FontColor.RED;style3.SetFont(font3);row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue("姓名");cell = row.CreateCell(1);cell.CellStyle = style2;cell.SetCellValue("入職日期\\星期");string[] Day = new string[] { "日", "一", "二", "三", "四", "五", "六" };int workDay = 0;for (int i = 1; i <= days; i++){DateTime time = Convert.ToDateTime(year.ToString() + "-" + month.ToString() + "-" + i.ToString());string week = Day[Convert.ToInt32(time.DayOfWeek.ToString("d"))].ToString();cell = row.CreateCell(i + 1);if (week == "六" || week == "日"){cell.CellStyle = style3;}else{cell.CellStyle = style2;}//合計工作日if (week != "六" && week != "日"){workDay++;}cell.SetCellValue(week);}cell = row.CreateCell(days + 2);cell.CellStyle = style2;cell.SetCellValue("班:" + workDay + " 休:" + (days - workDay));cell = row.CreateCell(days + 3);cell.SetCellValue("");//添加數據庫信息foreach (DataRow item in table.Rows){//字row = sheet.CreateRow(rowNum++);row.Height = 400;cell = row.CreateCell(0);cell.CellStyle = style2;cell.SetCellValue(item["Name"].ToString());//信息for (int i = 1; i <= days; i++){cell = row.CreateCell(i + 1);cell.CellStyle = style2;cell.SetCellValue(item["day" + i.ToString()].ToString() == "" ? "" : item["day" + i.ToString()].ToString());}//分cell = row.CreateCell(days + 2);cell.CellStyle = style2;cell.SetCellValue(item["lateOrEarly"].ToString() == "Empty" ? "" : item["lateOrEarly"].ToString());//天cell = row.CreateCell(days + 3);cell.CellStyle = style2;cell.SetCellValue(item["ActualDay"].ToString() == "Empty" ? "" : item["ActualDay"].ToString());//天cell = row.CreateCell(days + 4);cell.CellStyle = style2;cell.SetCellValue(item["outDay"].ToString() == "Empty" ? "" : item["outDay"].ToString());//補貼cell = row.CreateCell(days + 5);cell.CellStyle = style2;cell.SetCellValue(item["CarSubsidy"].ToString() == "Empty" ? "" : item["CarSubsidy"].ToString());//備注cell = row.CreateCell(days + 6);cell.CellStyle = style2;cell.SetCellValue(item["remark"].ToString() == "Empty" ? "" : item["remark"].ToString());}CellRangeAddress cellRangeAddress3 = new CellRangeAddress(rowNum, rowNum, 0, days + 2);sheet.AddMergedRegion(cellRangeAddress3);row = sheet.CreateRow(rowNum++);cell = row.CreateCell(0);cell.CellStyle = style3;cell.SetCellValue("備注。");int fileNum = 1;string filename = string.Format("{0}{1}年{2}月份信息.xls", shopname, year, month);f = new FileInfo(filepath + filename);while (f.Exists){filename = string.Format("{0}{1}年{2}月份信息({3}).xls", shopname, year, month, fileNum++);f = new FileInfo(filepath + filename);}using (var fs = f.OpenWrite()){workbook.Write(fs); //向打開的這個xls文件中寫入Sheet表并保存。 }return filename;}catch (Exception){throw;}}#endregion#region 通過文件獲取信息/// <summary>/// 將excel中的數據導入到DataTable中/// </summary>/// <param name="sheetName">excel工作薄sheet的名稱</param>/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>/// <returns>返回的DataTable</returns>public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn){IWorkbook workbook = null;FileStream fs = null;ISheet sheet = null;DataTable data = new DataTable();int startRow = 0;try{fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);if (fileName.IndexOf(".xlsx") > 0) // 2007版本workbook = new HSSFWorkbook(fs);else if (fileName.IndexOf(".xls") > 0) // 2003版本workbook = new HSSFWorkbook(fs);if (sheetName != null){sheet = workbook.GetSheet(sheetName);if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet {sheet = workbook.GetSheetAt(0);}}else{sheet = workbook.GetSheetAt(0);}if (sheet != null){IRow firstRow = sheet.GetRow(0);int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數if (isFirstRowColumn){for (int i = firstRow.FirstCellNum; i < cellCount; ++i){ICell cell = firstRow.GetCell(i);if (cell != null){string cellValue = cell.StringCellValue;if (cellValue != null){DataColumn column = new DataColumn(cellValue);data.Columns.Add(column);}}}startRow = sheet.FirstRowNum + 1;}else{firstRow = sheet.GetRow(2);cellCount = firstRow.LastCellNum;for (int i = firstRow.FirstCellNum; i < cellCount; ++i){ICell cell = firstRow.GetCell(i);if (cell != null){string cellValue = cell.StringCellValue;if (cellValue != null){DataColumn column = new DataColumn(cellValue);if (i == 0){column = new DataColumn("姓名");data.Columns.Add(column);}elsedata.Columns.Add(column);}}}startRow = sheet.FirstRowNum + 2;}//最后一列的標號int rowCount = sheet.LastRowNum;for (int i = startRow; i <= rowCount; ++i){IRow row = sheet.GetRow(i);if (row == null) continue; //沒有數據的行默認是null DataRow dataRow = data.NewRow();for (int j = row.FirstCellNum; j < cellCount; ++j){if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是nulldataRow[j] = row.GetCell(j).ToString();}data.Rows.Add(dataRow);}}return data;}catch (Exception ex){Console.WriteLine("Exception: " + ex.Message);return null;}}#endregion} }//例子#region 導入excel表并處理數據 /// <summary>/// 導入excel表并處理數據/// api/Schedual/ImportExceltoData/// </summary>/// <returns></returns> [HttpPost][ActionName("ImportExceltoData")]public IHttpActionResult ImportExceltoData(){try{PortraitApp = "~/FileLibs/Temp/";if (!Directory.Exists(HttpContext.Current.Server.MapPath(PortraitApp))){Directory.CreateDirectory(HttpContext.Current.Server.MapPath(PortraitApp));}HttpFileCollection files = HttpContext.Current.Request.Files;string name = "";string filename = "";string path = "";foreach (string key in files.AllKeys){HttpPostedFile file = files[key];if (string.IsNullOrEmpty(file.FileName) == false){int length = file.ContentLength;if (length > 2097152){throw new CustomException("上傳文件超過2M,請將上傳文件大小控制在2M內,謝謝");}string extension = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();if (extension != ".xls"){throw new CustomException("上傳文件擴展名不正確,請上傳xls格式的excel表");}name = DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + extension;//LoginVerifyModels usermodel = GetVerifyModel();string username = GetVerifyString();if (!string.IsNullOrEmpty(username)){name = username + extension;}path = HttpContext.Current.Server.MapPath(PortraitApp) + name;file.SaveAs(HttpContext.Current.Server.MapPath(PortraitApp) + name);filename = file.FileName;}}DataTable dt = new ExcelHelper().ExcelToDataTable(path, filename, false);if (dt == null || dt.Rows.Count < 2){ throw new CustomException("表格數據不能為空"); }List<SchedualInfoModel> list = insertTableSchedual(dt);if (list.Count > 0)return Json(Success(list));elsereturn Json(Success("導入失敗"));}catch (CustomException ce){return Json(getException(ce.Message));}catch (Exception ex){return Json(getException(ex));}}public List<SchedualInfoModel> insertTableSchedual(DataTable dt, string yearmonth = ""){int tempCount = 0;SchedualInfoModel schedualInfo = new SchedualInfoModel();string keyword = "";string loginid = "";string shopname = "";int count = dt.Rows.Count - 1;DateTime dtnow = DateTime.Now;string nowyearmonth = dtnow.Year.ToString() + dtnow.Month.ToString();//獲取年,月try{yearmonth = dt.Columns[1].ColumnName;shopname = dt.Rows[0][0].ToString().Trim();if (string.IsNullOrEmpty(shopname)){ throw new Exception("表格格式有誤,店名不能為空"); }for (int i = 2; i < count; i++){schedualInfo.year_month = yearmonth;schedualInfo.name = dt.Rows[i][0].ToString();schedualInfo.addtime = DateTime.Now.ToString();//string tempphone = dt.Rows[i]["手機"].ToString(); var counsoler = dbo.bk_Counselor.Where(c => c.CounselorName == schedualInfo.name && c.ShopId > 0 && c.IsDisplay == true).FirstOrDefault();var shop = dbo.bk_Shop.Where(c => c.ShopId == counsoler.ShopId).FirstOrDefault();if (shop == null || shopname != shop.ShopName){shop = dbo.bk_Shop.Where(c => c.ShopName == shopname).FirstOrDefault();counsoler = dbo.bk_Counselor.Where(c => c.CounselorName == schedualInfo.name && c.ShopId == shop.ShopId && c.IsDisplay == true).FirstOrDefault();}#region 導入excel表并處理數據 /// <summary>/// 導入excel表并處理數據/// api/Schedual/ImportExceltoData/// </summary>/// <returns></returns> [HttpPost][ActionName("ImportExceltoData")]public IHttpActionResult ImportExceltoData(){try{PortraitApp = "~/FileLibs/Temp/";if (!Directory.Exists(HttpContext.Current.Server.MapPath(PortraitApp))){Directory.CreateDirectory(HttpContext.Current.Server.MapPath(PortraitApp));}HttpFileCollection files = HttpContext.Current.Request.Files;string name = "";string filename = "";string path = "";foreach (string key in files.AllKeys){HttpPostedFile file = files[key];if (string.IsNullOrEmpty(file.FileName) == false){int length = file.ContentLength;if (length > 2097152){throw new CustomException("上傳文件超過2M,請將上傳文件大小控制在2M內,謝謝");}string extension = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();if (extension != ".xls"){throw new CustomException("上傳文件擴展名不正確,請上傳xls格式的excel表");}name = DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + extension;//LoginVerifyModels usermodel = GetVerifyModel();string username = GetVerifyString();if (!string.IsNullOrEmpty(username)){name = username + extension;}path = HttpContext.Current.Server.MapPath(PortraitApp) + name;file.SaveAs(HttpContext.Current.Server.MapPath(PortraitApp) + name);filename = file.FileName;}}DataTable dt = new ExcelHelper().ExcelToDataTable(path, filename, false);if (dt == null || dt.Rows.Count < 2){ throw new CustomException("表格數據不能為空"); }List<SchedualInfoModel> list = insertTableSchedual(dt);if (list.Count > 0)return Json(Success(list));elsereturn Json(Success("導入失敗"));}catch (CustomException ce){return Json(getException(ce.Message));}catch (Exception ex){return Json(getException(ex));}}public List<SchedualInfoModel> insertTableSchedual(DataTable dt, string yearmonth = ""){int tempCount = 0;SchedualInfoModel schedualInfo = new SchedualInfoModel();string keyword = "";string loginid = "";string shopname = "";int count = dt.Rows.Count - 1;DateTime dtnow = DateTime.Now;string nowyearmonth = dtnow.Year.ToString() + dtnow.Month.ToString();//獲取年,月try{yearmonth = dt.Columns[1].ColumnName;shopname = dt.Rows[0][0].ToString().Trim();if (string.IsNullOrEmpty(shopname)){ throw new Exception("表格格式有誤,店名不能為空"); }for (int i = 2; i < count; i++){schedualInfo.year_month = yearmonth;schedualInfo.name = dt.Rows[i][0].ToString();schedualInfo.addtime = DateTime.Now.ToString();//string tempphone = dt.Rows[i]["手機"].ToString(); var counsoler = dbo.bk_Counselor.Where(c => c.CounselorName == schedualInfo.name && c.ShopId > 0 && c.IsDisplay == true).FirstOrDefault();var shop = dbo.bk_Shop.Where(c => c.ShopId == counsoler.ShopId).FirstOrDefault();if (shop == null || shopname != shop.ShopName){shop = dbo.bk_Shop.Where(c => c.ShopName == shopname).FirstOrDefault();counsoler = dbo.bk_Counselor.Where(c => c.CounselorName == schedualInfo.name && c.ShopId == shop.ShopId && c.IsDisplay == true).FirstOrDefault();}if (counsoler == null){continue;}if (shop == null){ continue; }schedualInfo.shopid = shop.ShopId.ToString();schedualInfo.shopname = shop.ShopName.ToString();keyword = shop.ShopName;loginid = shop.AcountId.ToString();schedualInfo.uid = counsoler.CounselorID.ToString();//隱藏的店員不排班if (counsoler.IsDisplay == false){ continue; }//名字錯誤不排班if (string.IsNullOrEmpty(schedualInfo.name)){continue;}//無店鋪ID不排班if (string.IsNullOrEmpty(schedualInfo.shopid)){continue;}//店名不存在不排班if (string.IsNullOrEmpty(schedualInfo.shopname)){continue;}//顧問ID不存在不排班 if (string.IsNullOrEmpty(schedualInfo.uid)){ continue; }schedualInfo.entryDate = dt.Rows[i][1].ToString();//記錄入職日期schedualInfo.CarSubsidy = dt.Rows[i]["車費補貼"].ToString();schedualInfo.entryDate = dt.Rows[i]["法定節(jié)日加班/天"].ToString();schedualInfo.ActualDay = dt.Rows[i]["實際出勤/天"].ToString();schedualInfo.lateOrEarly = dt.Rows[i]["遲到/早退/分"].ToString();schedualInfo.remark = dt.Rows[i]["備注"].ToString();//schedualInfo.outDay = dt.Rows[i]["outDay"].ToString();//schedualInfo.station = dt.Rows[i]["station"].ToString();//schedualInfo.wages = dt.Rows[i]["wages"].ToString(); schedualInfo.day1 = dt.Rows[i]["1號"].ToString();schedualInfo.day2 = dt.Rows[i]["2號"].ToString();schedualInfo.day3 = dt.Rows[i]["3號"].ToString();schedualInfo.day4 = dt.Rows[i]["4號"].ToString();schedualInfo.day5 = dt.Rows[i]["5號"].ToString();schedualInfo.day6 = dt.Rows[i]["6號"].ToString();schedualInfo.day7 = dt.Rows[i]["7號"].ToString();schedualInfo.day8 = dt.Rows[i]["8號"].ToString();schedualInfo.day9 = dt.Rows[i]["9號"].ToString();schedualInfo.day10 = dt.Rows[i]["10號"].ToString();schedualInfo.day11 = dt.Rows[i]["11號"].ToString();schedualInfo.day12 = dt.Rows[i]["12號"].ToString();schedualInfo.day13 = dt.Rows[i]["13號"].ToString();schedualInfo.day14 = dt.Rows[i]["14號"].ToString();schedualInfo.day15 = dt.Rows[i]["15號"].ToString();schedualInfo.day16 = dt.Rows[i]["16號"].ToString();schedualInfo.day17 = dt.Rows[i]["17號"].ToString();schedualInfo.day18 = dt.Rows[i]["18號"].ToString();schedualInfo.day19 = dt.Rows[i]["19號"].ToString();schedualInfo.day20 = dt.Rows[i]["20號"].ToString();schedualInfo.day21 = dt.Rows[i]["21號"].ToString();schedualInfo.day22 = dt.Rows[i]["22號"].ToString();schedualInfo.day23 = dt.Rows[i]["23號"].ToString();schedualInfo.day24 = dt.Rows[i]["24號"].ToString();schedualInfo.day25 = dt.Rows[i]["25號"].ToString();schedualInfo.day26 = dt.Rows[i]["26號"].ToString();schedualInfo.day27 = dt.Rows[i]["27號"].ToString();schedualInfo.day28 = dt.Rows[i]["28號"].ToString();try{schedualInfo.day29 = dt.Rows[i]["29號"].ToString();schedualInfo.day30 = dt.Rows[i]["30號"].ToString();schedualInfo.day31 = dt.Rows[i]["31號"].ToString();}catch { }ExcelUpdateSchedualInfo(schedualInfo);tempCount++;}List<SchedualInfoModel> scheduallist = schedual.getSchedualByShopName(loginid, yearmonth, "2");if (keyword != ""){ scheduallist = scheduallist.Where(c => c.name.Contains(keyword) || c.shopname.Contains(keyword)).ToList(); }return scheduallist;}catch (CustomException ce){throw ce;}catch (Exception ex){throw ex;}}/// <summary>/// 修改用戶排班信息/// </summary>/// <param name="schedualInfo"></param>/// <returns></returns>internal int ExcelUpdateSchedualInfo(SchedualInfoModel schedualInfo){int sheid = schedualInfo.ID.ToIntForPage();int shopid = schedualInfo.shopid.ToIntForPage();int uid = schedualInfo.uid.ToIntForPage();string year_month = schedualInfo.year_month.Trim();if (uid == 0){throw new CustomException("傳入顧問參數錯誤");}tb_schedual schecdualmodel = dbo.tb_schedual.Where(c => c.uid == uid && c.year_month == year_month && c.name != null && shopid > 0 && c.shopname != null).FirstOrDefault();if (schecdualmodel == null){schecdualmodel = new tb_schedual(){shopid = shopid,uid = uid,year_month = year_month};dbo.tb_schedual.Add(schecdualmodel);}else{//判斷當月的修改次數//int updatecount = dbo.tb_schedual_UpdateInfo.Count(c => c.uid == uid && c.sid == shopid && c.yearmonth == year_month);//if (year_month == DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMM) && updatecount > 4)//{// throw new CustomException("當月修改次數已達到上限.");//}//插入修改歷史tb_schedual_UpdateInfo updateinfo = new tb_schedual_UpdateInfo(){sid = shopid,uid = uid,updateDate = DateTime.Now,yearmonth = year_month,remark = ""};dbo.tb_schedual_UpdateInfo.Add(updateinfo);}#endregionint result = dbo.SaveChanges();if (result > 0){//生成明細表--new SchedualService().UpdateCrewScheduling(schedualInfo);}return result;}#endregionExcelUpdateSchedualInfo(schedualInfo);tempCount++;}List<SchedualInfoModel> scheduallist = schedual.getSchedualByShopName(loginid, yearmonth, "2");if (keyword != ""){ scheduallist = scheduallist.Where(c => c.name.Contains(keyword) || c.shopname.Contains(keyword)).ToList(); }return scheduallist;}catch (CustomException ce){throw ce;}catch (Exception ex){throw ex;}}/// <summary>/// 修改信息/// </summary>/// <param name="schedualInfo"></param>/// <returns></returns>internal int ExcelUpdateSchedualInfo(SchedualInfoModel schedualInfo){int sheid = schedualInfo.ID.ToIntForPage();int shopid = schedualInfo.shopid.ToIntForPage();int uid = schedualInfo.uid.ToIntForPage();string year_month = schedualInfo.year_month.Trim();if (uid == 0){throw new CustomException("傳入參數錯誤");}schedual schecdualmodel = dbo.schedual.Where(c => c.uid == uid && c.year_month == year_month && c.name != null && shopid > 0 && c.shopname != null).FirstOrDefault();if (schecdualmodel == null){schecdualmodel = new tb_schedual(){shopid = shopid,uid = uid,year_month = year_month};dbo.tb_schedual.Add(schecdualmodel);}else{//判斷當月的修改次數//int updatecount = dbo.tb_schedual_UpdateInfo.Count(c => c.uid == uid && c.sid == shopid && c.yearmonth == year_month);//if (year_month == DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMM) && updatecount > 4)//{// throw new CustomException("當月修改次數已達到上限.");//}//插入修改歷史 dbo.tb_UpdateInfo.Add(updateinfo);}#region 賦值 #endregionint result = dbo.SaveChanges();if (result > 0){//生成明細表--new SchedualService().UpdateCrewScheduling(schedualInfo);}return result;} View Codejson 轉化輔助類
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization;namespace mofa.commom {public class JSONHelper{/// <summary> /// 對象轉JSON /// </summary> /// <param name="obj">對象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj){JavaScriptSerializer jss = new JavaScriptSerializer();jss.MaxJsonLength = Int32.MaxValue;jss.RecursionLimit = Int32.MaxValue;try{return jss.Serialize(obj);}catch (Exception ex){throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);}}/// <summary> /// 數據表轉鍵值對集合 www.2cto.com /// 把DataTable轉成 List集合, 存每一行 /// 集合中放的是鍵值對字典,存每一列 /// </summary> /// <param name="dt">數據表</param> /// <returns>哈希表數組</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt){List<Dictionary<string, object>> list= new List<Dictionary<string, object>>();foreach (DataRow dr in dt.Rows){Dictionary<string, object> dic = new Dictionary<string, object>();foreach (DataColumn dc in dt.Columns){dic.Add(dc.ColumnName, dr[dc.ColumnName]);}list.Add(dic);}return list;}/// <summary> /// 數據集轉鍵值對數組字典 /// </summary> /// <param name="dataSet">數據集</param> /// <returns>鍵值對數組字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds){Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();foreach (DataTable dt in ds.Tables)result.Add(dt.TableName, DataTableToList(dt));return result;}/// <summary> /// 數據表轉JSON /// </summary> /// <param name="dataTable">數據表</param> /// <returns>JSON字符串</returns> public static string DataTableToJSON(DataTable dt){return ObjectToJSON(DataTableToList(dt));}/// <summary> /// JSON文本轉對象,泛型方法 /// </summary> /// <typeparam name="T">類型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定類型的對象</returns> public static T JSONToObject<T>(string jsonText){JavaScriptSerializer jss = new JavaScriptSerializer();jss.MaxJsonLength = Int32.MaxValue;jss.RecursionLimit = Int32.MaxValue;try{return jss.Deserialize<T>(jsonText);}catch (Exception ex){throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);}}/// <summary> /// 將JSON文本轉換為數據表數據 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText){return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);}/// <summary> /// 將JSON文本轉換成數據行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText){return JSONToObject<Dictionary<string, object>>(jsonText);}/// <summary>/// 將接送對象字符串轉化成對象集合/// </summary>/// <typeparam name="TEntity"></typeparam>/// <param name="jsonText"></param>/// <returns></returns>public static List<TEntity> ListFromJSON<TEntity>(string jsonText){List<TEntity> modellist = new List<TEntity>();DataContractJsonSerializer _Json = new DataContractJsonSerializer(modellist.GetType());byte[] _Using = System.Text.Encoding.UTF8.GetBytes(jsonText);System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_Using);_MemoryStream.Position = 0;modellist = (List<TEntity>)_Json.ReadObject(_MemoryStream);return modellist;}} } View Codetxtlog記錄輔助類
private static StreamWriter sw1;/// <summary>/// Txt操作/// </summary>/// <param name="url">更新內容</param>/// <param name="name">更新txt名</param>/// <param name="fails">更新文件夾</param>public static void UrlTxt(string content, string name, string fails){//string y = AppDomain.CurrentDomain.BaseDirectory;//獲取當前程序的位置// string fileStr1 = y.Replace("\\bin\\Debug\\", fails);// fileStr1 += fails;// string fileStr1 = "F:\\自有商品獲取發(fā)布\\"+ fails;string fileStr1 = fails;//獲取txt所在文件 System.IO.Directory.CreateDirectory(fileStr1);DirectoryInfo dir = new DirectoryInfo(fileStr1);dir.Create();//自行判斷一下是否存在。string fileStr = fileStr1 + "\\" + name + ".txt";if (!File.Exists(fileStr)){FileStream fs1 = new FileStream(fileStr, FileMode.Create, FileAccess.Write);//創(chuàng)建寫入文件StreamWriter sw = new StreamWriter(fs1);sw.WriteLine(content);sw.Close();fs1.Close();}else{sw1 = File.AppendText(fileStr);sw1.WriteLine(content);sw1.Close();}}public static void WriteLog(string msg){string now = DateTime.Now.ToString("yyyyMMdd");//每一天分開保存string logpath = System.Configuration.ConfigurationManager.AppSettings["logpath"].ToString();string dirPath = logpath + now + "\\log" + "\\";//string txtpath = "F:\\FilePath\\PackageSvr\\";WriteLog(msg, "Worklog.txt", dirPath);//WriteLog(dirPath, "Worklog.txt", txtpath); }public static void WriteLog(string msg, string logName, string dirPath){if (!Directory.Exists(dirPath)){Directory.CreateDirectory(dirPath);}string filePath = dirPath + logName;//如果存在就添加一些文本內容 StreamWriter sw1;sw1 = File.AppendText(filePath);msg = msg + " ------- " + DateTime.Now.ToString() + "\r\n\r\n";sw1.Write(msg);sw1.Close();//Envirement.NewLine} View Codepost&&get提交api輔助類
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml; using System.Xml.Serialization;namespace mofa.commom {public class MethodHelper{/// <summary>/// 生成隨機數/// </summary>/// <param name="Length"></param>/// <param name="Sleep"></param>/// <retur public static string GetRandomNumber(int Length, bool Sleep) {if (Sleep) System.Threading.Thread.Sleep(3);string result = "";System.Random random = new Random();for (int i = 0; i < Length; i++){result += random.Next(10).ToString();}return result;}/// <summary>/// GET方式調用接口/// </summary>/// <param name="Url">要請求Url</param>/// <returns></returns>public static string RequestUrlByGET(string Url){string strHtml = "";try{HttpWebRequest wr;System.GC.Collect();wr = (HttpWebRequest)WebRequest.Create(Url);wr.KeepAlive = false;wr.Timeout = 100000000;wr.Method = "GET";wr.Credentials = CredentialCache.DefaultCredentials;HttpWebResponse wres = (HttpWebResponse)wr.GetResponse();if (wres.StatusCode != HttpStatusCode.RequestTimeout){strHtml = new StreamReader(wres.GetResponseStream()).ReadToEnd();wres.Close();wres = null;wr.Abort();wr = null;}else{throw new Exception("請求超時!");}}catch (WebException ex){throw new Exception(ex.Message);}return strHtml;}/// <summary>/// POST方式調用接口/// </summary>/// <param name="Url">要請求Url</param>/// <returns></returns>public static string RequestUrlByPOST(string Url, string postData = "UTF-8"){string strHtml = "";try{HttpWebRequest wr;System.GC.Collect();wr = (HttpWebRequest)WebRequest.Create(Url);wr.Headers.Add("charset:utf-8");var encoding = Encoding.GetEncoding("utf-8");byte[] bytes = encoding.GetBytes(postData);wr.Method = "POST";wr.Timeout = Int32.MaxValue;wr.Credentials = CredentialCache.DefaultCredentials;wr.ContentType = "text/xml";wr.ContentLength = bytes.Length;wr.ServicePoint.Expect100Continue = false;using (Stream requestStream = wr.GetRequestStream()){requestStream.Write(bytes, 0, bytes.Length);}using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse()){if (response.StatusCode == HttpStatusCode.OK && wr.HaveResponse){if (response != null){using (Stream stream = response.GetResponseStream())//獲取返回的字符流格式 {using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))//解決亂碼:設置utf-8字符格式 {if (sr != null){strHtml = sr.ReadToEnd();}}}}}}}catch (WebException ex){throw new Exception(ex.Message);}return strHtml;}/// <summary>/// POST方式調用接口/// </summary>/// <param name="Url">要請求Url</param>/// <returns></returns>public static string RequestUrlByPOSTWithParam(string Url, string Parameter){string strHtml = "";try{HttpWebRequest wr;System.GC.Collect();wr = (HttpWebRequest)WebRequest.Create(Url);//ASCIIEncoding encoding = new ASCIIEncoding();byte[] bytes = Encoding.UTF8.GetBytes(Parameter);//encoding.GetBytes(codestr);wr.Method = "POST";//wr.KeepAlive = false;//wr.ServicePoint.ConnectionLimit = 300;//wr.AllowAutoRedirect = true;//wr.ReadWriteTimeout = 10000;wr.Timeout = Int32.MaxValue;wr.Credentials = CredentialCache.DefaultCredentials;wr.ContentType = "application/json";wr.Accept = "application/xml";wr.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode("OpenStack"));wr.ContentLength = bytes.Length;wr.ServicePoint.Expect100Continue = false;using (Stream requestStream = wr.GetRequestStream()){requestStream.Write(bytes, 0, bytes.Length);}using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse()){if (response.StatusCode == HttpStatusCode.OK && wr.HaveResponse){if (response != null){using (Stream stream = response.GetResponseStream())//獲取返回的字符流格式 {using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))//解決亂碼:設置utf-8字符格式 {if (sr != null){strHtml = sr.ReadToEnd();}}}}}}}catch (WebException ex){throw new Exception(ex.Message);}return strHtml;}/// <summary>/// xml string 反序列化成對象/// </summary>public static T xmldeserialize<T>(string xmlstring){T t = default(T);XmlSerializer xmlserializer = new XmlSerializer(typeof(T));using (Stream xmlstream = new MemoryStream(Encoding.UTF8.GetBytes(xmlstring))){using (XmlReader xmlreader = XmlReader.Create(xmlstream)){object obj = xmlserializer.Deserialize(xmlreader);t = (T)obj;}}return t;}/// <summary>/// 時間戳轉為C#格式時間/// </summary>/// <param name=”timeStamp”></param>/// <returns></returns>public static DateTime GetTime(string timeStamp){DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));long lTime = long.Parse(timeStamp + "0000000");TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);}/// <summary>/// DateTime時間格式轉換為Unix時間戳格式/// </summary>/// <param name=”time”></param>/// <returns></returns>public static int ConvertDateTimeInt(System.DateTime time){System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));return (int)(time - startTime).TotalSeconds;}} } View Code字符串輔助類
using System; using System.Security.Cryptography; using System.Text;namespace mofa.commom {public static class StringHelper{#region 字符串加密/// <summary>/// MD5加密/// </summary>/// <param name="str"></param>/// <returns></returns>public static string ToMd5(this string str){return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");}public static string CreateMD5(this string source){string str = "";byte[] buffer = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(source));for (int i = 0; i < buffer.Length; i++){str = str + buffer[i].ToString("X");}return str;}/// <summary>/// Hash加密/// </summary>/// <param name="str"></param>/// <returns></returns>public static string ToHash(this string str){byte[] strBytes = Encoding.UTF8.GetBytes(str);byte[] hashbytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(strBytes);string hashString = Convert.ToBase64String(hashbytes);return hashString;}/// <summary>/// Hash加鹽加密/// </summary>/// <param name="str"></param>/// <returns></returns>public static string ToSaltHash(this string str, out string salt){salt = Guid.NewGuid().ToString();byte[] strtSaltBytes = Encoding.UTF8.GetBytes(str + salt);byte[] hashbytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(strtSaltBytes);string hashString = Convert.ToBase64String(hashbytes);return hashString;}#endregion#region 時間格式轉換public static string ToStringByDatetime(this DateTime dttm, DateTimeType dtt){string datetimetype = "";#region 分類switch (dtt){case DateTimeType.StandardyyyyMMddHHmmss:datetimetype = "yyyy-MM-dd HH:mm:ss";break;case DateTimeType.StandardyyyyMMddHHmm:datetimetype = "yyyy-MM-dd HH:mm";break;case DateTimeType.StandardyyyyMMdd:datetimetype = "yyyy-MM-dd";break;case DateTimeType.StandardyyyyMM:datetimetype = "yyyy-MM";break;case DateTimeType.Standardyyyy:datetimetype = "yyyy";break;case DateTimeType.StandardMMdd:datetimetype = "MM-dd";break;case DateTimeType.StandardHHmmss:datetimetype = "HH:mm:ss";break;case DateTimeType.StandardHHmm:datetimetype = "HH:mm";break;case DateTimeType.Standardmmss:datetimetype = "mm:ss";break;case DateTimeType.yyyyMMddHHmmss:datetimetype = "yyyyMMddHHmmss";break;case DateTimeType.yyyyMMdd:datetimetype = "yyyyMMdd";break;case DateTimeType.yyyyMM:datetimetype = "yyyyMM";break;case DateTimeType.yyMMdd:datetimetype = "yyMMdd";break;case DateTimeType.yyMM:datetimetype = "yyMM";break;case DateTimeType.HHmmss:datetimetype = "HHmmss";break;case DateTimeType.HHmm:datetimetype = "HHmm";break;case DateTimeType.MM:datetimetype = "MM";break;case DateTimeType.dd:datetimetype = "dd";break;case DateTimeType.HH:datetimetype = "HH";break;case DateTimeType.mm:datetimetype = "mm";break;case DateTimeType.ss:datetimetype = "ss";break;case DateTimeType.yyMMddHHmmss:datetimetype = "yyMMddHHmmss";break;case DateTimeType.yyMMddHHmm:datetimetype = "yyMMddHHmm";break;case DateTimeType.yyyyMMddHHmm:datetimetype = "yyyyMMddHHmm";break;default:datetimetype = "";break;}#endregionreturn dttm.ToString(datetimetype);}#endregion#region 整型數據轉換public static int ToIntForPage(this string str){int result = 0;if (!int.TryParse(str, out result)){try{result = Convert.ToInt32(str);}catch (Exception ex){result = 0;}}return result;}/// <summary>/// 小數轉換/// </summary>/// <param name="str"></param>/// <returns></returns>public static decimal ToDecimal(this string str){decimal result = 0;if (!decimal.TryParse(str, out result)){try{result = Convert.ToInt32(str);}catch (Exception ex){result = 0;}}return result;}/// <summary>/// 時間轉換/// </summary>/// <param name="str"></param>/// <returns></returns>public static DateTime ToDateTime(this string str){DateTime result = new DateTime(1900, 1, 1);if (!DateTime.TryParse(str, out result)){try{result = Convert.ToDateTime(str);}catch (Exception ex){result = new DateTime(1900, 1, 1);}}return result;}/// <summary>/// 時間轉換/// </summary>/// <param name="str"></param>/// <returns></returns>public static DateTime ToDateTime(this string str, DateTimeType dtt){DateTime result = new DateTime(1900, 1, 1);switch (dtt){#region MyRegioncase DateTimeType.StandardyyyyMMddHHmmss:break;case DateTimeType.StandardyyyyMMddHHmm:break;case DateTimeType.StandardyyyyMMdd:break;case DateTimeType.StandardyyyyMM:break;case DateTimeType.Standardyyyy:break;case DateTimeType.StandardMMdd:break;case DateTimeType.StandardHHmmss:break;case DateTimeType.StandardHHmm:break;case DateTimeType.Standardmmss:break;case DateTimeType.yyyyMMddHHmmss:break;case DateTimeType.yyyyMMdd:break;case DateTimeType.yyyyMM:str = str.Substring(0, 4) + "-" + str.Substring(4, 2) + "-01";break;case DateTimeType.yyMMdd:break;case DateTimeType.yyMM:break;case DateTimeType.HHmmss:break;case DateTimeType.HHmm:break;case DateTimeType.MM:break;case DateTimeType.dd:break;case DateTimeType.HH:break;case DateTimeType.mm:break;case DateTimeType.ss:break;case DateTimeType.yyMMddHHmmss:break;case DateTimeType.yyMMddHHmm:break;case DateTimeType.yyyyMMddHHmm:break;default:break;#endregion}if (!DateTime.TryParse(str, out result)){try{result = Convert.ToDateTime(str);}catch (Exception ex){result = new DateTime(1900, 1, 1);}}return result;}#endregion#region 整除有余則進一public static int ToDivision(double Molecule, double Denominator){int result = (Math.Ceiling(Molecule / Denominator)).ToString().ToIntForPage();return result;}#endregion}#region 時間格式枚舉/// <summary>/// 時間格式枚舉/// </summary>public enum DateTimeType{StandardyyyyMMddHHmmss = 1,StandardyyyyMMddHHmm = 2,StandardyyyyMMdd = 3,StandardyyyyMM = 4,Standardyyyy = 5,StandardMMdd = 6,StandardHHmmss = 7,StandardHHmm,Standardmmss,yyyyMMddHHmmss,yyyyMMdd,yyyyMM,yyMMdd,yyMM,HHmmss,HHmm,MM,dd,HH,mm,ss,yyMMddHHmmss,yyMMddHHmm,yyyyMMddHHmm}#endregion } View Codetable輔助類
/// <summary>/// 將List轉換成DataTable/// </summary>/// <typeparam name="T"></typeparam>/// <param name="data"></param>/// <returns></returns>public static DataTable ToDataTable<T>(this IList<T> data){PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));DataTable dt = new DataTable();for (int i = 0; i < properties.Count; i++){PropertyDescriptor property = properties[i];dt.Columns.Add(property.Name, property.PropertyType);}object[] values = new object[properties.Count];foreach (T item in data){for (int i = 0; i < values.Length; i++){values[i] = properties[i].GetValue(item) == null ? DBNull.Value : properties[i].GetValue(item);}dt.Rows.Add(values);}return dt;}public static IList<TEntity> ConvertToModel(DataTable dt){IList<TEntity> ts = new List<TEntity>();// 定義集合Type type = typeof(TEntity); // 獲得此模型的類型string tempName = "";foreach (DataRow dr in dt.Rows){TEntity t = new TEntity();PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性foreach (PropertyInfo pi in propertys){tempName = pi.Name;if (dt.Columns.Contains(tempName)){if (!pi.CanWrite) continue;object value = dr[tempName];if (value != DBNull.Value)pi.SetValue(t, value, null);}}ts.Add(t);}return ts;}/// <summary> /// 對象轉JSON /// </summary> /// <param name="obj">對象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj){JavaScriptSerializer jss = new JavaScriptSerializer();jss.MaxJsonLength = Int32.MaxValue;jss.RecursionLimit = Int32.MaxValue;try{return jss.Serialize(obj);}catch (Exception ex){throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);}}/// <summary> /// 數據表轉鍵值對集合 www.2cto.com /// 把DataTable轉成 List集合, 存每一行 /// 集合中放的是鍵值對字典,存每一列 /// </summary> /// <param name="dt">數據表</param> /// <returns>哈希表數組</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt){List<Dictionary<string, object>> list= new List<Dictionary<string, object>>();foreach (DataRow dr in dt.Rows){Dictionary<string, object> dic = new Dictionary<string, object>();foreach (DataColumn dc in dt.Columns){dic.Add(dc.ColumnName, dr[dc.ColumnName]);}list.Add(dic);}return list;}/// <summary> /// 數據集轉鍵值對數組字典 /// </summary> /// <param name="dataSet">數據集</param> /// <returns>鍵值對數組字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds){Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();foreach (DataTable dt in ds.Tables)result.Add(dt.TableName, DataTableToList(dt));return result;}/// <summary> /// 數據表轉JSON /// </summary> /// <param name="dataTable">數據表</param> /// <returns>JSON字符串</returns> public static string DataTableToJSON(DataTable dt){return ObjectToJSON(DataTableToList(dt));}/// <summary> /// JSON文本轉對象,泛型方法 /// </summary> /// <typeparam name="T">類型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定類型的對象</returns> public static T JSONToObject<T>(string jsonText){JavaScriptSerializer jss = new JavaScriptSerializer();jss.MaxJsonLength = Int32.MaxValue;jss.RecursionLimit = Int32.MaxValue;try{return jss.Deserialize<T>(jsonText);}catch (Exception ex){throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);}}/// <summary> /// 將JSON文本轉換為數據表數據 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText){return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);}/// <summary> /// 將JSON文本轉換成數據行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText){return JSONToObject<Dictionary<string, object>>(jsonText);}/// <summary>/// 將接送對象字符串轉化成對象集合/// </summary>/// <typeparam name="TEntity"></typeparam>/// <param name="jsonText"></param>/// <returns></returns>public static List<TEntity> ListFromJSON<TEntity>(string jsonText){List<TEntity> modellist = new List<TEntity>();DataContractJsonSerializer _Json = new DataContractJsonSerializer(modellist.GetType());byte[] _Using = System.Text.Encoding.UTF8.GetBytes(jsonText);System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_Using);_MemoryStream.Position = 0;modellist = (List<TEntity>)_Json.ReadObject(_MemoryStream);return modellist;} View Code?
轉載于:https://www.cnblogs.com/yaozhiguang/p/7214553.html
總結
- 上一篇: 今日小程序推荐:香蕉打码-二维码随意生成
- 下一篇: 洛谷P1133 教主的花园 动态规划