使用NPOI導出Excel引起異常(IsReadOnly = 「book.IsReadOnly」引起了類型「System.NotImplementedException」的異常)

前言:前端

本人調式npoi導入、導出試用成功後,引入到項目中,導入完美運行,可是導出怎麼樣都看不到如今的頁面,並且瀏覽器和後臺都沒有報任務錯誤,讓人好事納悶,後來去調式,發如今除了一個IsReadOnly = 「book.IsReadOnly」引起了類型「System.NotImplementedException」的異常)。最開始的懷疑是這裏問題,而後去調式環境看也是存在的,而後就天然想到的前端問題。最後果真是前端出了問題,在導出的點擊函數裏寫了異步ajax蠢死了,後來異步ajax改爲  完美導出。web

 

NPOI 經常使用本版本下載:ajax

 http://download.csdn.net/detail/whk311/6465879數據庫

 

 

mynpoi導入導出封裝:json

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using System.IO;
using NPOI.HPSF;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using NPOI.SS.Util;
using System.Drawing;
using System.Data;
using System.Reflection;
using System.Linq.Expressions;
using GTJ.Utility.MyNPOI;

namespace MyNPOI.Excel
{
    internal class ExcelHelper
    {
        #region "構造函數"
        internal ExcelHelper() { }
        #endregion

        #region "私有字段"
        /// <summary>
        /// 自定義顏色
        /// </summary>
        HSSFPalette XlPalette = null;
        /// <summary>
        /// 要導出的excel對象
        /// </summary>
        private HSSFWorkbook workbook = null;
        /// <summary>
        /// 要導出的excel對象屬性
        /// </summary>
        private HSSFWorkbook Workbook
        {
            get
            {
                if (workbook == null)
                {
                    workbook = new HSSFWorkbook();
                }
                return workbook;
            }
            set { workbook = value; }
        }
        /// <summary>
        /// 要導出的excel對象中的一個表
        /// </summary>
        private ISheet sheet = null;
        /// <summary>
        /// 導出的內容部分的樣式
        /// </summary>
        HSSFCellStyle cellStyle = null;
        /// <summary>
        /// 表頭行數
        /// </summary>
        int rowHeadNum = 0;
        /// <summary>
        /// 行數,方便內容正確在行插入
        /// </summary>
        private List<IRow> rowList = new List<IRow>();

        private List<GroupClass> gCell = null;
        private List<GroupClass> GCell
        {
            get { return gCell; }
            set { gCell = value; }
        }

        /// <summary>
        /// 整個表格border樣式,默認solid
        /// </summary>
        private BorderStyle wholeBorderStyle = BorderStyle.Thin;
        private BorderStyle WholeBorderStyle
        {
            get { return wholeBorderStyle; }
            set { wholeBorderStyle = value; }
        }
        /// <summary>
        /// 整個表格border顏色,默認黑色
        /// </summary>
        private short wholeBorderColor = HSSFColor.Black.Index;
        public short WholeBorderColor
        {
            get { return wholeBorderColor; }
            set { wholeBorderColor = value; }
        }
        /// <summary>
        /// 表頭單元格字體是否加粗
        /// </summary>
        private short headFontWeight = (short)FontBoldWeight.Bold;
        /// <summary>
        /// 表頭單元格字體是否加粗
        /// </summary>
        public short HeadFontWeight
        {
            get { return headFontWeight; }
            set { headFontWeight = value; }
        }


        #endregion

        /// <summary>
        /// 建立表頭
        /// </summary>
        /// <param name="json">相似json的字符串</param>
        internal void SetHead(string json,List<GroupClass> group,int column)
        {
            Root T =Utility.JsonUtility.DecodeObject<Root>(json);
            //肯定表頭行數
            if (group != null && column > -1)
            {
                     int headRow = T.root.rowspan.Value;
                     int indexs = headRow;
                    foreach (var item in group)
                    {
                        item.column = column;
                        if (indexs == headRow)
                        {
                            item.index = headRow;
                        }
                        else
                        {
                            item.index = indexs;
                        }
                        indexs = item.index.Value + item.groupCount.Value;
                    }
                    SetGroupCell(group);
            }
            if (sheet == null)
            {
                sheet = Workbook.CreateSheet(T.root.sheetname);
            }
            sheet.DisplayGridlines = true;
            if (T.root.defaultwidth.HasValue)
            {
                //設置表格默認寬高
                sheet.DefaultColumnWidth = T.root.defaultwidth.Value; //12
            }
            if (T.root.defaultheight.HasValue)
            {
                //設置表格默認行高
                sheet.DefaultRowHeight = (short)T.root.defaultheight.Value; //25
            }
            if (!string.IsNullOrEmpty(T.root.borderstyle))
            {
                string bStyle = T.root.borderstyle.Trim();
                if (!string.IsNullOrEmpty(bStyle))
                {
                    switch (bStyle)
                    {
                        case "none":
                            WholeBorderStyle = BorderStyle.None;
                            break;
                        case "solid":
                            WholeBorderStyle = BorderStyle.Thin;
                            break;
                        case "dashed":
                            WholeBorderStyle = BorderStyle.Dashed;
                            break;
                        case "dotted":
                            WholeBorderStyle = BorderStyle.Dotted;
                            break;
                        case "double":
                            WholeBorderStyle = BorderStyle.Double;
                            break;
                        default:
                            WholeBorderStyle = BorderStyle.Thin;
                            break;
                    }
                }
            }
            XlPalette = Workbook.GetCustomPalette();
            if (!string.IsNullOrEmpty(T.root.bordercolor))
            {
                Color co = ColorTranslator.FromHtml(T.root.bordercolor);
                XlPalette.SetColorAtIndex(HSSFColor.Plum.Index, (byte)co.R, (byte)co.G, (byte)co.B);
                WholeBorderColor = NPOI.HSSF.Util.HSSFColor.Plum.Index;//這句代碼根據16進制不起做用,起到顏色初始化
            }
         

            int rowN = Convert.ToInt32(T.root.rowspan);
            rowHeadNum = rowN ; 
            //建立行
            for (int i = 0; i < rowN; i++)
            {
                IRow temp = sheet.CreateRow(i);
                rowList.Add(temp);

            }
            //合併單元格
            //填充內容
            for (int i = 0; i < T.root.head.Count; i++)
            {
                //讀取最重要的區域,0=fromRow,1=toRow,2=fromColumn,3=toColumn
                AttributeList al = T.root.head[i];
                int[] c = al.cellregion.Split(',').ToIntArray();
                if (c[0] < c[1] || c[2] < c[3])   //例如1,1,2,2 第二行中的第3列,例如1,1,2,7 第二行中的(第3列到8列),合併列
                {
                    CellRangeAddress cellr = new CellRangeAddress(c[0], c[1], c[2], c[3]);
                    sheet.AddMergedRegion(cellr);
                    //設置邊框
                    ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellr, WholeBorderStyle, WholeBorderColor);
                }
            }
            //填充內容
            for (int i = 0; i < T.root.head.Count; i++)
            {
                //讀取最重要的區域,0=fromRow,1=toRow,2=fromColumn,3=toColumn
                AttributeList al = T.root.head[i];
                int[] c = al.cellregion.Split(',').ToIntArray();
                //計算title要插入的位置的索引
                int txtIndex = -1;
                int txtRow = -1;

                if ((c[0] == c[1] && c[2] == c[3]) || (c[0] == c[1] && c[2] < c[3]))
                { //例如1,1,2,2 第二行中的第3列,例如1,1,2,7 第二行中的(第3列到8列)
                    txtIndex = c[2];
                    txtRow = c[0];
                    ICell cell1 = rowList[txtRow].CreateCell(txtIndex);

                    //設置單元格的高度
                    if (!T.root.defaultheight.HasValue&& al.height.HasValue)
                    {
                        rowList[txtRow].HeightInPoints = (short)al.height.Value ;
                    }
                    SetHeadCellBold(al);
                    cell1.SetCellValue(al.title);
                    cell1.CellStyle = SetCellStyle(al);

                }
                if (c[0] < c[1] && c[2] == c[3]) //合併c[0]到c[1]行 ,列沒變 ,   'cellregion':'0,1,1,1',
                {
                    txtIndex = c[2];
                    txtRow = c[0];
                    ICell cell1 = rowList[txtRow].CreateCell(txtIndex);
                    //設置單元格的高度
                    if (!T.root.defaultheight.HasValue && al.height.HasValue)
                    {
                        rowList[txtRow].Height = (short)(al.height.Value * 20);
                    }
                    SetHeadCellBold(al);
                    cell1.SetCellValue(al.title);
                    cell1.CellStyle = SetCellStyle(al);
                }
                if (c[0] < c[1] && c[2] < c[3]) //合併c[0]到c[1]行 ,列沒變 ,   'cellregion':'4,5,2,4',
                {
                    txtIndex = c[2];
                    txtRow = c[0];
                    ICell cell1 = rowList[txtRow].CreateCell(txtIndex);
                    SetHeadCellBold(al);
                    //設置單元格的高度
                    if (!T.root.defaultheight.HasValue && al.height.HasValue)
                    {
                        rowList[txtRow].Height = (short)(al.height.Value * 20);
                    }
                    cell1.SetCellValue(al.title);
                    cell1.CellStyle = SetCellStyle(al);
                }

                //設置單元格的寬度
                if (!T.root.defaultwidth.HasValue && al.width.HasValue)
                {
                    sheet.SetColumnWidth(i, al.width.Value * 256);
                }
            }


        }
        /// <summary>
        /// 設置表頭單元格字體是否加粗,默認加粗
        /// </summary>
        /// <param name="al"></param>
        private void SetHeadCellBold(AttributeList al)
        {
            if (string.IsNullOrEmpty(al.fontweight)) {
                HeadFontWeight = (short)FontBoldWeight.Bold;
            }
            else
            {
                switch (al.fontweight)
                {
                    case "bold":
                        HeadFontWeight = (short)FontBoldWeight.Bold;
                        break;
                    case "none":
                        HeadFontWeight = (short)FontBoldWeight.None;
                        break;
                    case "normal":
                        HeadFontWeight = (short)FontBoldWeight.Normal;
                        break;
                    default:
                        HeadFontWeight = (short)FontBoldWeight.Bold;
                        break;
                }
            }
        }

        /// <summary>
        /// web導出excel
        /// </summary>
        /// <typeparam name="T">實體類</typeparam>
        /// <param name="list">導出的列表對象</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="titles">標題</param>
        /// <param name="fieldFuncs">字段委託,若是不傳則T的所有屬性</param>
        internal void ExportToWeb<T>(List<T> list, string fileName, string[] titles, string headJson, params Func<T, string>[] fieldFuncs)
        {
            ///建立表頭
            SetHead(headJson,null,-1);
            ///轉換數據源
            DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
            ///開始導出
            WebCommonExport(dtSource, fileName);
            System.GC.Collect();
        }
        /// <summary>
        /// web導出excel
        /// </summary>
        /// <typeparam name="T">實體類</typeparam>
        /// <param name="list">導出的列表對象</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="titles">標題</param>
        /// <param name="fieldFuncs">字段委託,若是不傳則T的所有屬性</param>
        internal void ExportToWeb<T>(List<T> list, string fileName, string[] titles, string headJson,List<GroupClass> group,int groupColumn,params Func<T, string>[] fieldFuncs)
        {
            ///建立表頭
            SetHead(headJson, group,groupColumn);
            ///轉換數據源
            DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
            ///開始導出
            WebCommonExport(dtSource, fileName);
            System.GC.Collect();
        }

        /// <summary>
        /// 保存到本地
        /// </summary>
        /// <typeparam name="T">實體類</typeparam>
        /// <param name="list">導出的列表對象</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="titles">標題</param>
        /// <param name="fieldFuncs">字段委託,若是不傳則T的所有屬性</param>
        internal void ExportToLocal<T>(List<T> list, string fileName, string[] titles, string headJson, params Func<T, string>[] fieldFuncs)
        {
            ///建立表頭
            SetHead(headJson, null, -1);
            ///轉換數據源
            DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
            ///開始導出
            LocalCommonExport(dtSource, fileName);
            System.GC.Collect();
        }
        /// <summary>
        /// 保存到本地
        /// </summary>
        /// <typeparam name="T">實體類</typeparam>
        /// <param name="list">導出的列表對象</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="titles">標題</param>
        /// <param name="fieldFuncs">字段委託,若是不傳則T的所有屬性</param>
        internal void ExportToLocal<T>(List<T> list, string fileName, string[] titles, string headJson, List<GroupClass> group, int groupColumn, params Func<T, string>[] fieldFuncs)
        {
            ///建立表頭
            SetHead(headJson, group,groupColumn);
            ///轉換數據源
            DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
            ///開始導出
            LocalCommonExport(dtSource, fileName);
            System.GC.Collect();
        }
        /// DataTable導出到Excel的MemoryStream,#CommonExport,所有都是字符串處理
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表頭文本</param>
        internal void WebCommonExport(DataTable dtSource, string fileName)
        {
            BeforeExport(dtSource);
            //轉換好後開始提供下載
            Workbook.ExportToWeb(fileName);
        }

        /// DataTable導出到Excel的MemoryStream,#CommonExport,所有都是字符串處理
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="fileName">文件存儲路徑</param>
        /// 
        internal void LocalCommonExport(DataTable dtSource, string fileName)
        {
            BeforeExport(dtSource);
            //轉換好後開始保存本地
            Workbook.ExportToLocal(fileName);
        }

        /// <summary>
        /// 整合數據
        /// </summary>
        /// <param name="dtSource"></param>
        private void BeforeExport(DataTable dtSource)
        {
            HSSFCellStyle dateStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
            cellStyle = SetContentFormat(600, 10);
            //取得列寬
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = rowList.Count();
            dtSource.Rows.RemoveAt(0); //移除第一行,由於有表頭了



            foreach (DataRow row in dtSource.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);
                    newCell.CellStyle = cellStyle;
                    string drValue = row[column].ToString();
                    newCell.SetCellValue(drValue);

                }
                rowIndex++;
            }

            try
            {
                int temp = 0;
                if (GCell != null && dtSource.Rows.Count > 0)
                {
                    foreach (GroupClass gCell in GCell)
                    {

                        IRow row = sheet.GetRow(gCell.index.Value);//獲取工做表第一行
                        ICell cell = row.GetCell(gCell.column);//獲取行的第COLUMN列
                        string cellValue = cell.ToString();//獲取列的值
                        //若是設置了分組,目前只能一種
                        temp=gCell.index.Value+gCell.groupCount.Value-1;
                        CellRangeAddress cellr = new CellRangeAddress(gCell.index.Value, temp, gCell.column, gCell.column);
                        sheet.AddMergedRegion(cellr);
                        //設置邊框
                        ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellr, WholeBorderStyle, WholeBorderColor);
                        ICell ce = row.CreateCell(gCell.column);
                        ce.CellStyle = cellStyle;
                        ce.SetCellValue(cellValue);
                    }
                }
            }
            catch
            {
                throw new Exception("GroupCell某些屬性可能爲空了!");
            }

        }


        #region 輔助幫助,設置樣式和 轉換顏色
        static bool cellColorBug = true; //關於NPOI自定義顏色設置有個bug,這個能夠保證第一次單元格設置不會始終黑色
        /// <summary>
        /// 設置單元格基本樣式
        /// </summary>
        /// <param name="al"></param>
        private HSSFCellStyle SetCellStyle(AttributeList al)
        {
            HSSFCellStyle headStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
            XlPalette = Workbook.GetCustomPalette();
            headStyle.Alignment = string.IsNullOrEmpty(al.align) ? HorizontalAlignment.Center : al.align.ToHorAlign(); //默認水平居中
            headStyle.VerticalAlignment = string.IsNullOrEmpty(al.valign) ? VerticalAlignment.Center : al.valign.ToVerAlign();//垂直居中
            headStyle.FillPattern = FillPattern.SolidForeground; //默認填充整個背景顏色
            bool forc = string.IsNullOrEmpty(al.bgcolor); //是否有背景顏色
            if (forc)
            {
                headStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index; //默認灰色
            }
            else
            {
                headStyle.FillForegroundColor = GetColorIndex(Workbook, al.bgcolor);//這句代碼根據16進制不起做用,起到顏色初始化
                if (cellColorBug)
                {
                    Color co = ColorTranslator.FromHtml(al.bgcolor);
                    XlPalette.SetColorAtIndex(HSSFColor.Pink.Index, (byte)co.R, (byte)co.G, (byte)co.B);
                    headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                    cellColorBug = false;
                }
            }

            //設置單元格border
            headStyle.BorderRight = headStyle.BorderLeft = headStyle.BorderBottom = headStyle.BorderTop = WholeBorderStyle;
            headStyle.BottomBorderColor = headStyle.RightBorderColor = headStyle.LeftBorderColor = headStyle.TopBorderColor = WholeBorderColor;
            bool fontc = string.IsNullOrEmpty(al.fontcolor); //是否有字體顏色
            //設置單元格字體
            HSSFFont font = (HSSFFont)Workbook.CreateFont();
            if (fontc)
            {
                font.Color = 8; //默認黑色
            }
            else
            {
                font.Color = GetColorIndex(Workbook, al.fontcolor);//這句代碼根據16進制不起做用,起到顏色初始化
                if (cellColorBug)
                {
                    Color co = ColorTranslator.FromHtml(al.fontcolor);
                    XlPalette.SetColorAtIndex(HSSFColor.Pink.Index, (byte)co.R, (byte)co.G, (byte)co.B);
                    font.Color = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                    cellColorBug = false;
                }
            }

      
            font.FontHeightInPoints = al.fontsize ?? 11; //設置字體大小
            font.Boldweight =HeadFontWeight;
            font.FontName = string.IsNullOrWhiteSpace(al.fontName) ? "宋體" : al.fontName;//設置字體爲宋體
            font.IsItalic = al.IsItalic.HasValue && al.IsItalic.Value ? true : false;//是不是斜體
            font.IsStrikeout = al.IsStrikeout.HasValue && al.IsStrikeout.Value ? true : false;//是否有中間線
            font.Underline = al.Underline.HasValue && al.Underline.Value ? FontUnderlineType.Single :FontUnderlineType.None;//設置下劃線
            headStyle.SetFont(font);
            return headStyle;
        }

        /// <summary>
        /// 根據十六進制顏色得到顏色索引
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        private short GetColorIndex(HSSFWorkbook workbook, string color)
        {
            Color co = ColorTranslator.FromHtml(color);

            return GetXLColour(workbook, co);
        }

        //得到excel中的顏色索引
        private short GetXLColour(HSSFWorkbook workbook, System.Drawing.Color SystemColour)
        {
            short s = 0;
            HSSFPalette XlPalette = workbook.GetCustomPalette();
            HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
            //if (XlColour == null)
            //{
            //    if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
            //    {
            //        if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
            //        {
            //            NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE = 64;
            //            NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;
            //            XlColour = XlPalette.AddColor(SystemColour.R, SystemColour.G, SystemColour.B);
            //        }
            //        else
            //        {
            //            XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
            //        }

            //        s = XlColour.Indexed;
            //    }

            //}
            //else
            //    s = XlColour.Indexed;

            return s;
        }

        #endregion

        #region 設置excel文件基本屬性
        /// <summary>
        /// 文件基本屬性
        /// </summary>
        /// <param name="company">公司名稱,默認 慧擇網</param>
        /// <param name="author">做者信息,默認 慧擇</param>
        /// <param name="ApplicationName">建立程序信息</param>
        /// <param name="LastAuthor">xls文件最後保存者信息</param>
        /// <param name="Comments">填加xls文件做者信息,備註</param>
        /// <param name="title">填加xls文件標題信息</param>
        /// <param name="Subject">填加文件主題信息</param>
        /// <returns>一個初始化的Excel Workbook對象</returns>
        internal void SetWorkbook(ExcelProperty ep)
        {
            #region 右擊文件 屬性信息
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            ///公司
            dsi.Company = ep.Company;
            dsi.Manager = ep.Manager;
            dsi.Category = ep.Catagory;
            Workbook.DocumentSummaryInformation = dsi;
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Author = ep.Author; //填加xls文件做者信息
            si.ApplicationName = ep.ApplicationName; //填加xls文件建立程序信息
            si.LastAuthor = ep.LastAuthor; //填加xls文件最後保存者信息
            si.Comments = ep.Comments; //填加xls文件做者信息
            si.Title = ep.Title; //填加xls文件標題信息
            si.Subject = ep.Subject;//填加文件主題信息
            si.Keywords = ep.KeyWord;
            si.CreateDateTime = DateTime.Now;
            si.Comments = ep.Comments;
            Workbook.SummaryInformation = si;
            #endregion
        }
        /// <summary>
        /// 初始化顯示的內容的單元格統一的樣式
        /// </summary>
        /// <param name="fontweight">字體粗細</param>
        /// <param name="fontsize">字體大小</param>
        internal HSSFCellStyle SetContentFormat(short fontweight = 600, short fontsize = 10)
        {
            cellStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
            //設置單元格border
            cellStyle.BorderRight = cellStyle.BorderLeft = cellStyle.BorderBottom = cellStyle.BorderTop = WholeBorderStyle;
            cellStyle.BottomBorderColor = cellStyle.RightBorderColor = cellStyle.LeftBorderColor = cellStyle.TopBorderColor = WholeBorderColor;
            cellStyle.Alignment = HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            IFont font = Workbook.CreateFont();
            font.FontHeightInPoints = fontsize;
            font.Boldweight = fontweight;
            cellStyle.SetFont(font);
            return cellStyle;
        }
        #endregion

        #region 設置分組信息
        internal void SetGroupCell(List<GroupClass> ce)
        {
            GCell = ce;
        }
        #endregion

    }

    /// <summary>
    /// 拓展類
    /// </summary>
    public static class Extend
    {

        /// <summary>
        /// 泛型列表轉成DataTable
        /// </summary>
        /// <typeparam name="T">泛型實體</typeparam>
        /// <param name="list">要轉換的列表</param>
        /// <param name="titles">標題</param>
        /// <param name="fieldFuncs">字段委託</param>
        /// <returns></returns>
        internal static DataTable ToDataTable<T>(this List<T> list, string[] titles, params Func<T, string>[] fieldFuncs)
        {
            if (fieldFuncs.Length > 0)
            {
                if (titles == null || fieldFuncs.Length != titles.Length)
                {
                    throw new Exception("titles不能爲空且必須與導出字段一一對應");
                }

                DataTable dt = new DataTable();
                //標題行
                DataRow headerDataRow = dt.NewRow();
                for (int i = 0; i < fieldFuncs.Length; i++)
                {
                    dt.Columns.Add(new DataColumn());
                    headerDataRow[i] = titles[i];
                }
                dt.Rows.Add(headerDataRow);

                //內容行
                foreach (T item in list)
                {
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < fieldFuncs.Length; i++)
                    {
                        dr[i] = fieldFuncs[i](item);
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
            else
            {
                Type listType = typeof(T);
                PropertyInfo[] properties = listType.GetProperties();
                if (properties.Length != titles.Length)
                {
                    throw new Exception("titles不能爲空且必須與導出字段一一對應");
                }

                DataTable dt = new DataTable();
                //標題行
                DataRow headerDataRow = dt.NewRow();
                for (int i = 0; i < properties.Length; i++)
                {
                    PropertyInfo property = properties[i];
                    dt.Columns.Add(new DataColumn());
                    headerDataRow[i] = titles[i];
                }
                dt.Rows.Add(headerDataRow);

                //內容行
                foreach (T item in list)
                {
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        dr[i] = properties[i].GetValue(item, null);
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }

        /// <summary>
        /// List轉DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        internal static DataTable ToDataTable<T>(this IEnumerable<T> list, string tableName)
        {
            //建立屬性的集合    
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //得到反射的入口    
            Type type = typeof(T);
            DataTable dt = new DataTable();
            dt.TableName = tableName;
            //把全部的public屬性加入到集合 並添加DataTable的列    
            System.Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in list)
            {
                //建立一個DataRow實例    
                DataRow row = dt.NewRow();
                //給row 賦值    
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable    
                dt.Rows.Add(row);
            }
            return dt;
        }

        /// <summary>
        /// 將WorkBook對象轉換成內存流
        /// </summary>
        /// <param name="wv"></param>
        /// <returns></returns>
        public static MemoryStream SaveToStream(this HSSFWorkbook wv)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                wv.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }

        internal static int[] ToIntArray(this string[] region)
        {
            ArrayList aList = new ArrayList();
            foreach (string i in region)
                aList.Add(Convert.ToInt32(i));
            return (int[])aList.ToArray(typeof(int));
        }

        internal static HorizontalAlignment ToHorAlign(this string str)
        {
            switch (str.ToLower())
            {
                case "center":
                    return HorizontalAlignment.Center;
                    break;
                case "left":
                    return HorizontalAlignment.Left;
                    break;
                case "right":
                    return HorizontalAlignment.Right;
                    break;
                default:
                    return HorizontalAlignment.Center;
                    break;
            }
            return HorizontalAlignment.Center;
        }

        internal static VerticalAlignment ToVerAlign(this string str)
        {
            switch (str.ToLower())
            {
                case "center":
                    return VerticalAlignment.Center;
                    break;
                case "top":
                    return VerticalAlignment.Top;
                    break;
                case "bottom":
                    return VerticalAlignment.Bottom;
                    break;
                default:
                    return VerticalAlignment.Center;
                    break;
            }
            return VerticalAlignment.Center;
        }

        /// <summary>
        ///  web導出excel
        /// </summary>
        /// <param name="hssf">已經被處理好的HSSFWorkbook對象</param>
        /// <param name="fileName">將要下載顯示的名字</param>
        public static void ExportToWeb(this HSSFWorkbook hssf, string fileName)
        {
            byte[] buffers = hssf.SaveToStream().GetBuffer();
            ExportToWebExcel(buffers, fileName);
        }

        /// <summary>
        /// 本地存儲到excel
        /// </summary>
        /// <param name="hssf">已經被處理好的HSSFWorkbook對象</param>
        /// <param name="fileName">文件名稱,請本身包含路徑,例如C:\\test.xls</param>
        public static void ExportToLocal(this HSSFWorkbook hssf, string fileName)
        {
            byte[] buffers = hssf.SaveToStream().GetBuffer();
            ExportToLocalExcel(buffers, fileName);
        }

        /// <summary>
        ///  本地存儲到excel
        /// </summary>
        /// <param name="buffers">文件二進制流</param>
        /// <param name="fileName">文件目錄例如C:\\test.xls</param>
        public static void ExportToLocalExcel(byte[] buffers, string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buffers, 0, buffers.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// web導出excel
        /// </summary>
        /// <param name="buffers">文件二進制流</param>
        /// <param name="fileName">文件名稱</param>
        public static void ExportToWebExcel(byte[] buffers, string fileName)
        {
            if (HttpContext.Current.Request.Browser.Type.IndexOf("IE") > -1)
            {
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" +
                    HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            }
            else
            {
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename*=utf-8'zh_cn'{0}", HttpUtility.UrlEncode(fileName)));
            }
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.BinaryWrite(buffers);
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            HttpContext.Current.Response.End();
        }


    }

    #region Excel屬性類
    /// <summary>
    /// 用於定義導出的excel屬性
    /// </summary>
    public class ExcelProperty
    {
        public ExcelProperty() { }
        /// <summary>
        /// 文件基本屬性
        /// </summary>
        /// <param name="company">公司名稱 默認AaronYang</param>
        /// <param name="author">做者信息,默認 楊洋</param>
        /// <param name="ApplicationName">建立程序信息</param>
        /// <param name="LastAuthor">xls文件最後保存者信息</param>
        /// <param name="Comments">填加xls文件做者信息,備註</param>
        /// <param name="title">填加xls文件標題信息</param>
        /// <param name="Subject">填加文件主題信息</param>
        /// <param name="keyWord">關鍵詞</param>
        /// <param name="catagory">類別</param>
        /// <param name="manager">經理</param>
        public ExcelProperty(string company, string author, string applicationName, string lastAuthor, string comments, string title, string subject, string keyWord, string catagory, string manager)
        {
            this.Company = company;
            this.Author = author;
            this.ApplicationName = applicationName;
            this.LastAuthor = lastAuthor;
            this.Comments = comments;
            this.Title = title;
            this.Subject = subject;
            this.Manager = manager;
            this.KeyWord = keyWord;
            this.Catagory = catagory;
        }
        /// <summary>
        /// 公司名稱,默認 AaronYang
        /// </summary>
        private string company = "AaronYang";
        /// <summary>
        /// 公司名稱,默認 AaronYang
        /// </summary>
        public string Company
        {
            get { return company; }
            set { company = value; }
        }
        /// <summary>
        /// 做者信息,默認 楊洋
        /// </summary>
        private string author = "楊洋";
        /// <summary>
        /// 做者信息,默認 楊洋
        /// </summary>
        public string Author
        {
            get { return author; }
            set { author = value; }
        }
        /// <summary>
        /// 建立程序信息
        /// </summary>
        private string applicationName = "";
        /// <summary>
        /// 建立程序信息
        /// </summary>
        public string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }
        /// <summary>
        /// xls文件最後保存者信息
        /// </summary>
        private string lastAuthor = "";
        /// <summary>
        /// xls文件最後保存者信息
        /// </summary>
        public string LastAuthor
        {
            get { return lastAuthor; }
            set { lastAuthor = value; }
        }
        /// <summary>
        ///填加xls文件做者信息,備註
        /// </summary>
        private string comments = "";
        /// <summary>
        ///填加xls文件做者信息,備註
        /// </summary>
        public string Comments
        {
            get { return comments; }
            set { comments = value; }
        }
        /// <summary>
        /// 填加xls文件標題信息
        /// </summary>
        private string title = "";
        /// <summary>
        /// 填加xls文件標題信息
        /// </summary>
        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        /// <summary>
        /// 填加文件主題信息
        /// </summary>
        private string subject = "";
        /// <summary>
        /// 填加文件主題信息
        /// </summary>
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }
        /// <summary>
        /// 關鍵字
        /// </summary>
        private string keyWord = "";
        /// <summary>
        /// 關鍵字
        /// </summary>
        public string KeyWord
        {
            get { return keyWord; }
            set { keyWord = value; }
        }
        /// <summary>
        /// 類別
        /// </summary>
        private string catagory = "";
        /// <summary>
        /// 類別
        /// </summary>
        public string Catagory
        {
            get { return catagory; }
            set { catagory = value; }
        }
        /// <summary>
        /// 經理
        /// </summary>
        private string manager = "";
        /// <summary>
        /// 經理
        /// </summary>
        public string Manager
        {
            get { return manager; }
            set { manager = value; }
        }

    }
    #endregion

    #region 定義Json表頭的格式
    /// <summary>
    /// 關於表頭單元格設置屬性:字體默認:黑體,字體大小默認12
    /// </summary>
    internal class AttributeList
    {
        /// <summary>
        /// 顯示的文字
        /// </summary>
        public string title { get; set; }
        /// <summary>
        /// 顯示方式
        /// </summary>
        public string align { get; set; }
        /// <summary>
        /// 垂直顯示方式
        /// </summary>
        public string valign { get; set; }
        /// <summary>
        /// 背景顏色.例如#000000
        /// </summary>
        public string bgcolor { get; set; }
        /// <summary>
        /// 字體大小
        /// </summary>
        public short? fontsize { get; set; }
        /// <summary>
        /// 字體顏色,例如#000000
        /// </summary>
        public string fontcolor { get; set; }
        /// <summary>
        /// 單元格合併位置,(fromRow,toRow,fromColumn,toColumn)
        /// </summary>
        public string cellregion { get; set; }
        /// <summary>
        /// 字體名稱
        /// </summary>
        public string fontName { get; set; }
        /// <summary>
        /// 表頭文字是否加粗,默認加粗
        /// </summary>
        public string fontweight { get; set; }
        /// <summary>
        /// 寬度
        /// </summary>
        public int? width { get; set; }
        /// <summary>
        /// 高度
        /// </summary>
        public int? height { get; set; }

        /// <summary>
        ///是不是斜體
        /// </summary>
        public bool? IsItalic { get; set; }
        /// <summary>
        /// 是否有中間線
        /// </summary>
        public bool? IsStrikeout { get; set; }
        /// <summary>
        /// 設置下劃線
        /// </summary>
        public bool? Underline { get; set; }

    }

    /// <summary>
    /// 合併組,暫時支持一列
    /// </summary>
    public class GroupClass
    {
        /// <summary>
        /// 從哪一行開始
        /// </summary>
        public int? index { get; set; }
        /// <summary>
        /// 分組後每組中多少個值
        /// </summary>
        public int?  groupCount{ get; set; }
        /// <summary>
        /// 要合併的那一列的索引
        ///  </summary>
        public int column { get; set; }

    }
    /// <summary>
    /// 報表表格頭部信息
    /// </summary>
    internal class HeadInfo
    {
        public IList<AttributeList> head { get; set; }
        public int? rowspan { get; set; }
        public string sheetname { get; set; }
        /// <summary>
        /// 默認單元格寬度
        /// </summary>
        public int? defaultwidth { get; set; }
        /// <summary>
        /// 默認行高度
        /// </summary>
        public int? defaultheight { get; set; }
        /// <summary>
        /// 默認黑色,表格邊框顏色
        /// </summary>
        public string bordercolor { get; set; }
        /// <summary>
        /// 邊框風格,默認 thin
        /// </summary>
        public string borderstyle { get; set; }
    }
    /// <summary>
    /// 根節點
    /// </summary>
    internal class Root
    {
        public HeadInfo root { get; set; }
    }

    #endregion

    /// <summary>
    /// excel 構建
    /// 仿照AutoMaper 調用方式
    /// 調用方式
    /// new ExportBuilder<CustomerInsureModel>()
    ///         .Column(c => c.InsureNum)
    ///         .Column(c => c.Applicant)
    ///         .Column(c => c.Insurant)
    ///         .Column(c => c.CompanyName)
    ///         .Column(c => c.ProdName)
    ///         .Column(c => c.InsureTime, c => c.InsureTime.Value.ToString("yyyy-MM-dd HH:mm"))
    ///         .Column(c => c.IsMergePay, c => c.IsMergePay ? c.OrderNum : string.Empty)
    ///         .Column(c => c.BuySinglePrice, c => c.BuySinglePrice.Value.ToString("0.00"))
    ///         .Column(c => c.OnlinePaymnet, c => c.OnlinePaymnet.GetDescription())
    ///         .Export(vdata.ToList(), "用戶投保信息.xls");
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ExportBuilder<T>
    {
        List<string> titles = new List<string>();
        //循環進行添加func字段的值
        List<Func<T, string>> funcs = new List<Func<T, string>>();
        private ExcelHelper excel;
        internal ExcelHelper Excel
        {
            get
            {
                if (excel == null)
                {
                    excel = new ExcelHelper();
                }
                return excel;
            }
            set { excel = value; }
        }

        /// <summary>
        /// 定義列
        /// 2012-08-15 支持 .Column(m => m.Platform01.ToString()) 寫法
        /// </summary>
        /// <param name="member">解析Display特性獲得列名,如不存在,則使用列名</param>
        /// <returns></returns>
        public ExportBuilder<T> Column(Expression<Func<T, string>> member)
        {
            //var memberParam = member.Body as MemberExpression;
            titles.Add(ExcelUtility.GetDisplayName(member.Body));
            var convert = member.Compile();
            funcs.Add(convert);
            return this;
        }
        public void SetTitleAndColumn(Expression<Func<T, string>> member)
        {
            titles.Add(ExcelUtility.GetDisplayName(member.Body));
            var convert = member.Compile();
            funcs.Add(convert);
        }
        /// <summary>
        /// 定義列
        /// </summary>
        /// <param name="member"></param>
        /// <param name="title">列名</param>
        /// <returns></returns>
        public ExportBuilder<T> Column(Expression<Func<T, string>> member, string title)
        {
            var memberParam = member.Body as MemberExpression;
            titles.Add(title);
            var convert = member.Compile();
            funcs.Add(convert);
            return this;
        }

        /// <summary>
        /// 定義列 
        /// </summary>
        /// <param name="member">解析Display特性獲得列名,如不存在,則使用列名</param>
        /// <param name="convert">定義數據輸出格式</param>
        /// <returns></returns>
        public ExportBuilder<T> Column(Expression<Func<T, object>> member, Func<T, string> convert)
        {
            //var memberParam = member.Body as MemberExpression;
            titles.Add(ExcelUtility.GetDisplayName(member.Body));
            funcs.Add(convert);
            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="member"></param>
        /// <param name="title">列名</param>
        /// <param name="convert">定義數據輸出格式</param>
        /// <returns></returns>
        public ExportBuilder<T> Column(Expression<Func<T, object>> member, string title, Func<T, string> convert)
        {
            var memberParam = member.Body as MemberExpression;
            titles.Add(title);
            funcs.Add(convert);
            return this;
        }

        /// <summary>
        /// 編輯已經添加的轉換
        /// </summary>
        /// <param name="name"></param>
        /// <param name="convert"></param>
        /// <returns></returns>
        public ExportBuilder<T> Edit(string name, Func<T, string> convert)
        {
            var index = titles.FindIndex(m => m == name);
            if (index > -1)
            {
                funcs[index] = convert;
            }
            return this;
        }
       
        /// <summary>
        /// 設置Excel屬性
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        public ExportBuilder<T> SetExcelProperty(ExcelProperty ext)
        {
            Excel.SetWorkbook(ext);
            return this;
        }

        /// <summary>
        /// 導出WEB
        /// </summary>
        /// <param name="list">數據源</param>
        /// <param name="fileName">文件名</param>
        /// <param name="headJosn">表頭JSON</param>
        public void Export(List<T> list, string fileName, string headJson)
        {
            Excel.ExportToWeb<T>(list, fileName, titles.ToArray(), headJson, funcs.ToArray());
        }
       /// <summary>
        /// 導出WEB,含分組
       /// </summary>
       /// <param name="list">數據源(分組後的)</param>
       /// <param name="fileName">文件名</param>
       /// <param name="headJosn">表頭JSON</param>
        /// <param name="group">分組集合</param>
        /// <param name="groupColumn">分組所在的列,索引從0開始</param>
        public void Export(List<T> list, string fileName, string headJson, List<GroupClass> group, int groupColumn)
        {
            Excel.ExportToWeb<T>(list, fileName, titles.ToArray(), headJson, group, groupColumn, funcs.ToArray());
        }
        /// <summary>
        /// 導出到本地存儲
        /// </summary>
        /// <param name="list">數據源</param>
        /// <param name="fileName">文件名</param>
        /// <param name="headJson">表頭JSON</param>
        public void ExportToLocal(List<T> list, string fileName, string headJson)
        {
            Excel.ExportToLocal<T>(list, fileName, titles.ToArray(), headJson, funcs.ToArray());
        }
        /// <summary>
        /// 導出到本地存儲,含分組
        /// </summary>
        /// <param name="list">數據源(分組後的)</param>
        /// <param name="fileName">文件名</param>
        /// <param name="headJson">表頭JSON</param>
        /// <param name="group">分組集合</param>
        /// <param name="groupColumn">分組所在的列,索引從0開始</param>
        public void ExportToLocal(List<T> list, string fileName, string headJson, List<GroupClass> group, int groupColumn)
        {
            Excel.ExportToLocal<T>(list, fileName, titles.ToArray(), headJson, group, groupColumn, funcs.ToArray());
        }
    }

}
using MyNPOI.Excel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace GTJ.Utility.MyNPOI.Excel
{
   public class ExcelUtility
    {
        private static IWorkbook workbook = null;
        
        public static void CreateWorkbook(Stream file)
        {
            workbook = WorkbookFactory.Create(file);
        }

        /// <summary>
        /// 解析Excel
        /// </summary>
        /// <param name="strFileName">Excel文件路徑</param>
        /// <param name="SheetIndex">sheet號</param>
        /// <param name="dataIndex">數據開始行</param>
        /// <param name="needHeader"></param>
        /// <returns></returns>
        public static List<StringBuilder> ImportExceltoList(int SheetIndex, int dataIndex)
        {
            int num = 0;
            try
            {
                List<StringBuilder> listTemp = new List<StringBuilder>();

                ISheet sheet = workbook.GetSheetAt(SheetIndex);
                int rows = sheet.LastRowNum;//得到總行數

                for (int i = dataIndex; i <= rows; i++)
                {
                    num = i;
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        break;
                    }
                    int cellnum = row.LastCellNum;//單元格數
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < cellnum; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell != null)
                        {
                            cell.SetCellType(CellType.String);//全都設置成String
                            string value = cell.StringCellValue;
                            sb.Append(value.Trim()).Append(";");

                        }
                        else
                        {
                            sb.Append(";");
                        }
                    }
                    listTemp.Add(sb);//每行數據以分號(;)隔開拼接成字符串存入list中       
                }
                return listTemp;
            }
            catch
            {
                GTJ.Utility.ScriptHelper.writer(System.Web.HttpContext.Current.Response, "導入Excel出錯,在" + num + "行有錯誤,請檢查");
            }
            return null;
        }

        /// <summary>
        /// 進行數據庫的導出   
        /// </summary>
        /// <typeparam name="T">model 屬性值</typeparam>
        /// <param name="list"></param>
        /// <param name="fileName"></param>
        /// <param name="headJson"></param>
        /// <param name="funcs"></param>
        public static void ExportToLocal<T>(List<T> list, string fileName, string headJson,  params Expression<Func<T,string>>[] funcs)
        {
            ExportBuilder<T>  ExportBuild = new ExportBuilder<T>();
            for(var i=0;i< funcs.Length; i++)
            {
                //設置對應的title和列的狀況
                ExportBuild.SetTitleAndColumn(funcs[i]);

            }
            ExportBuild.ExportToLocal(list,fileName,headJson);
        }
        /// <summary>
        ///  導入到web端
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="fileName"></param>
        /// <param name="headJson"></param>
        /// <param name="funcs"></param>
        public static void ExportToWeb<T>(List<T> list, string fileName, string headJson, params Expression<Func<T, string>>[] funcs)
        {
            ExportBuilder<T> ExportBuild = new ExportBuilder<T>();
            for (var i = 0; i < funcs.Length; i++)
            {
                //設置對應的title和列的狀況
                ExportBuild.SetTitleAndColumn(funcs[i]);

            }
            ExportBuild.Export(list, fileName, headJson);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.IO;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.ComponentModel;

namespace GTJ.Utility.MyNPOI
{
    /// <summary>   
    ///JsonUtility 的摘要說明   
    /// </summary>   
    public class Utility
    {
        /// <summary>   
        /// Json工具類   
        /// </summary>   
        public static class JsonUtility
        {
            /// <summary>   
            /// 添加時間轉換器   
            /// </summary>   
            /// <param name="serializer"></param>   
            private static void AddIsoDateTimeConverter(JsonSerializer serializer)
            {
                IsoDateTimeConverter idtc = new IsoDateTimeConverter();
                //定義時間轉化格式   
                idtc.DateTimeFormat = "yyyy-MM-dd";
                //idtc.DateTimeFormat = "yyyy-MM-dd";   
                serializer.Converters.Add(idtc);
            }

            /// <summary>   
            /// Json轉換配置   
            /// </summary>   
            /// <param name="serializer"></param>   
            private static void SerializerSetting(JsonSerializer serializer)
            {
                serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //serializer.NullValueHandling = NullValueHandling.Ignore;   
                //serializer.MissingMemberHandling = MissingMemberHandling.Ignore;   
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;   
            }

            /// <summary>   
            /// 返回結果消息編碼   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="sucess"></param>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="data"></param>   
            /// <returns></returns>   
            public static string ReturnMessage(bool sucess, int total, string message, string exMessage, string data)
            {
                message = message.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", "");
                exMessage = exMessage.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", "");

                return string.Format("{{success:{0},total:{1},data:{2},message:\"{3}\",exMessage:\"{4}\"}}",
                    sucess.ToString().ToLower(), total, data, message, exMessage);
            }

            /// <summary>   
            /// 返回失敗信息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <returns></returns>   
            public static string ReturnFailureMessage(string message, string exMessage)
            {
                return ReturnMessage(false, 0, message, exMessage, "[]");
            }

            /// <summary>   
            /// 返回失敗信息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <returns></returns>   
            public static string ReturnFailureMessageTouch(string message, string exMessage)
            {
                return "{\"success\":\"false\",\"msg\":\"" + exMessage + "\"}";
            }

            /// <summary>   
            /// 返回成功信息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="total"></param>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="objList"></param>   
            /// <returns></returns>   
            public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, List<T> objList)
            {
                string data = ListToJson<T>(objList);
                return ReturnMessage(true, total, message, exMessage, data);
            }

            public static string ReturnSuccessMessageTouch<T>(T obj)
            {
                string data = ObjectToJson<T>(obj);
                return data;
            }

            /// <summary>   
            /// 返回成功信息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="total"></param>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="objList"></param>   
            /// <returns></returns>   
            public static string ReturnSuccessMessage(string message, string exMessage)
            {
                return ReturnMessage(true, 0, message, exMessage, "[]");
            }

            /// <summary>   
            /// 返回成功信息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="total"></param>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="objList"></param>   
            /// <returns></returns>   
            public static string ReturnSuccessMessageTouch(string message, string exMessage)
            {
                return "{\"success\":\"true\",\"msg\":\"" + message + "\"}";
            }



            /// <summary>   
            /// 返回成功信息   
            /// </summary>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="data">JSON 對象</param>   
            /// <returns></returns>   
            public static string ReturnSuccessMessage(string message, string exMessage, string data)
            {
                return ReturnMessage(true, 0, message, exMessage, "[" + data + "]");
            }

            /// <summary>   
            /// 返回成功消息   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="total"></param>   
            /// <param name="message"></param>   
            /// <param name="exMessage"></param>   
            /// <param name="obj"></param>   
            /// <returns></returns>   
            public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, T obj)
            {
                string data = ObjectToJson<T>(obj);
                return ReturnMessage(true, total, message, exMessage, data);
            }

            /// <summary>   
            /// 把對象列表編碼爲Json數據   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="objList"></param>   
            /// <returns></returns>   
            public static string ListToJson<T>(List<T> objList)
            {
                JsonSerializer serializer = new JsonSerializer();
                SerializerSetting(serializer);
                AddIsoDateTimeConverter(serializer);

                using (TextWriter sw = new StringWriter())
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, objList);
                    return sw.ToString();
                }
            }

            /// <summary>   
            ///  把一個對象編碼爲Json數據   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="obj"></param>   
            /// <returns></returns>   
            public static string ObjectToJson<T>(T obj)
            {
                JsonSerializer serializer = new JsonSerializer();
                SerializerSetting(serializer);
                AddIsoDateTimeConverter(serializer);

                using (TextWriter sw = new StringWriter())
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, obj);
                    return sw.ToString();
                }
            }


            /// <summary>   
            /// 根據傳入的Json數據,解碼爲對象(一個)   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="data"></param>   
            /// <returns></returns>   
            public static T DecodeObject<T>(string data)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                AddIsoDateTimeConverter(serializer);
                StringReader sr = new StringReader(data);
                return (T)serializer.Deserialize(sr, typeof(T));


            }

            /// <summary>   
            /// 功能同DecodeObject   
            /// </summary>   
            /// <typeparam name="T"></typeparam>   
            /// <param name="data"></param>   
            /// <returns></returns>   
            public static List<T> DecodeObjectList<T>(string data)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                AddIsoDateTimeConverter(serializer);
                StringReader sr = new StringReader(data);
                return (List<T>)serializer.Deserialize(sr, typeof(List<T>));
            }

            public static string EncodeAjaxResponseJson(string jsonString, string callback)
            {
                String responseString = "";
                //判斷是否jsonp調用   
                if (!String.IsNullOrEmpty(callback))
                {
                    //jsonp調用,須要封裝回調函數,並返回   
                    responseString = callback + "(" + jsonString + ")";
                }
                else
                {
                    //普通ajax調用,直接返回Json數據   
                    responseString = jsonString;
                }

                return responseString;
            }

            public static string ExtGridSortInfo(string property, string direction)
            {
                return string.Format("[{{\"property\":\"{0}\",\"direction\":\"{1}\"}}]", property, direction);
            }

        }



    }

    public static class ExcelUtility
    {
        /// <summary>
        /// [Display(Name = "")]
        /// 得到類屬性中標記的名稱
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static string GetDisplayName(Expression expr)
        {
            var memberParam = expr as MemberExpression;
            if (memberParam != null)
            {
                return GetDisplayName(memberParam);
            }
            var unary = expr as UnaryExpression;
            if (unary != null)
            {
                return GetDisplayName(unary.Operand as MemberExpression);
            }
            var call = expr as MethodCallExpression;
            if (call != null)
            {
                return GetDisplayName(call.Object as MemberExpression);
            }

            return string.Empty;

        }

        /// <summary>
        /// [Display(Name = "記住賬號")]
        /// 得到類屬性中標記的中文名
        /// </summary>
        /// <param name="memberParam"></param>
        /// <returns></returns>
        private static string GetDisplayName(MemberExpression memberParam)
        {
            var name = memberParam.Member.Name;
            var property = memberParam.Member.ReflectedType.GetProperty(name);
            var displays = property.GetCustomAttributes(typeof(DisplayAttribute), false);
            if (displays == null || displays.Length == 0)
                return property.Name;
            else
                return (displays[0] as DisplayAttribute).Name;
        }
    }

    public static class typeUtility
    {
        /// <summary>
        /// 獲取枚舉的描述
        /// </summary>
        /// <param name="enumType">枚舉類型</param>
        /// <param name="fieldName">枚舉字段名稱</param>
        /// <returns></returns>
        public static string GetDescription(Type enumType, string fieldName)
        {
            if (!enumType.IsEnum)
                throw new InvalidOperationException("親,必須是Enum類型哦,請檢查類型是否正確哈。");

            FieldInfo field = enumType.GetField(fieldName);
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
            typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : fieldName;
        }

        /// <summary>
        /// 獲取枚舉的描述
        /// </summary>
        /// <typeparam name="TEnum">枚舉類型</typeparam>
        /// <param name="enumObject">枚舉對象</param>
        /// <returns></returns>
        public static string GetDescription<TEnum>(this TEnum enumObject)
        {
            FieldInfo field = enumObject.GetType().GetField(enumObject.ToString());
            if (field == null)
            {
                return "";
            }
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
                typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : enumObject.ToString();
        }
    }
}
相關文章
相關標籤/搜索