码迷,mamicode.com
首页 > Windows程序 > 详细

c# 开发工具类

时间:2017-07-20 23:53:02      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:xlsx   参数错误   nbsp   缓存   use   英文   时间格式   hash   tps   

stemp0 快速开发,需要使用很多小函数,方便快捷,保留适合自己的方法,会使开发效率提升

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 Code

excel 辅助类

技术分享
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>
        /// 创建工作簿
        /// </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;

            //创建工作薄  
            IWorkbook workbook = new HSSFWorkbook(); ;
            //string extension = System.IO.Path.GetExtension(fileName);


            //HSSFWorkbook workbook = new HSSFWorkbook();
            //Stream ms = new MemoryStream();

            //创建一个名称为Payment的工作表
            ISheet paymentSheet = workbook.CreateSheet("Payment");

            //数据源
            DataTable tbPayment = dt;

            //头部标题
            IRow paymentHeaderRow = paymentSheet.CreateRow(0);

            //循环添加标题

            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);

                //循环添加列的对应内容
                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;

            //创建工作薄  
            IWorkbook workbook = new HSSFWorkbook(); ;
            //string extension = System.IO.Path.GetExtension(fileName);


            //HSSFWorkbook workbook = new HSSFWorkbook();
            //Stream ms = new MemoryStream();

            //创建一个名称为Payment的工作表
            ISheet paymentSheet = workbook.CreateSheet("Payment");

            //数据源
            DataTable tbPayment = dt;

            //头部标题
            IRow paymentHeaderRow = paymentSheet.CreateRow(0);

            //循环添加标题

            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);

                //循环添加列的对应内容
                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;

            //创建工作薄  
            IWorkbook workbook = new HSSFWorkbook(); ;

            //创建一个名称为Payment的工作表
            ISheet paymentSheet = workbook.CreateSheet("Payment");

            //数据源
            DataTable tbPayment = dt;

            //头部标题
            IRow paymentHeaderRow = paymentSheet.CreateRow(0);

            //循环添加标题

            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);

            //    //循环添加列的对应内容
            //    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);

                //循环添加列的对应内容
                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++)
                        {
                            //设置一个合并单元格区域,使用上下左右定义CellRangeAddress区域
                            //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);

                //创建表
                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);

                //创建表
                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);
                                    }
                                    else
                                        data.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) //同理,没有数据的单元格都默认是null
                                dataRow[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));
                else
                    return 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));
                else
                    return 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]["法定节日加班/天"].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);
            }

          

            #endregion

            int result = dbo.SaveChanges();

            if (result > 0)
            {
                //生成明细表--
                new SchedualService().UpdateCrewScheduling(schedualInfo);
            }

            return result;

        }

        #endregion
                    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("传入参数错误");
            }

            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 赋值      
            #endregion

            int result = dbo.SaveChanges();

            if (result > 0)
            {
                //生成明细表--
                new SchedualService().UpdateCrewScheduling(schedualInfo);
            }

            return result;

        }
View Code

json 转化辅助类

技术分享
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 Code

txtlog记录辅助类

技术分享
  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:\\自有商品获取发布\\"+ 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);//创建写入文件
                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 Code

post&&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;
            }
            #endregion

            return 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 MyRegion
                case 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 Code

table辅助类

技术分享
 /// <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

 

c# 开发工具类

标签:xlsx   参数错误   nbsp   缓存   use   英文   时间格式   hash   tps   

原文地址:http://www.cnblogs.com/yaozhiguang/p/7214553.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!