using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Data;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.Web;

namespace PushPlatform.Common.Util
{
    /// <summary>
    /// Excel操作辅助类
    /// </summary>
    public class ExcelHelper
    {
        #region DataTable导出Excel
        /// <summary>
        /// DataTable导出Excel
        /// </summary>
        /// <param name="table">要导出的datatable</param>
        /// <returns>内存流</returns>
        public static MemoryStream RenderToExcel(DataTable table)
        {
            MemoryStream ms = new MemoryStream();
            using (table)
            {
                #region

                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);
                IFont fontHeader = workbook.CreateFont();
                //设置格式
                fontHeader.FontHeightInPoints = 10;
                fontHeader.FontName = "微软雅黑";
                fontHeader.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                ICellStyle headerStyle = workbook.CreateCellStyle();
                headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
                headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                headerStyle.SetFont(fontHeader);

                //读取datatable列，填充到EXCEL
                foreach (DataColumn column in table.Columns)
                {
                    ICell cell = headerRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(column.Caption);
                    cell.CellStyle = headerStyle;
                }
                int rowIndex = 1;
                //循环每一行数据
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (DataColumn column in table.Columns)
                    {
                        ICell cell = dataRow.CreateCell(column.Ordinal);
                        cell.SetCellValue(row[column].ToString());
                        if (table.Columns.Contains("ISSTYLE"))
                        {
                            string MsIndex = table.Rows[rowIndex - 1]["ISSTYLE"].ToString();
                            if (string.IsNullOrEmpty(MsIndex))
                            {
                                continue;
                            }
                            string[] str = MsIndex.Split(',');
                            foreach (string item in str)
                            {
                                string[] strIndex = item.Split(':');
                                if (Convert.ToInt32(strIndex[0]) == cellIndex)
                                {
                                    ICellStyle cellStyle = workbook.CreateCellStyle();
                                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                                    IFont font = workbook.CreateFont();
                                    font.FontHeightInPoints = 10;
                                    font.FontName = "微软雅黑";
                                    if (table.Columns.Contains("FONTBOLD") && (row["FONTBOLD"].ToString() == "1"))
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                                    }
                                    else
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
                                    }
                                    cellStyle.SetFont(font);
                                    switch (strIndex[1])
                                    {
                                        case "RED":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
                                            break;
                                        case "WHITE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            break;
                                        case "BLACK":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            break;
                                        case "GREEN":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                                            break;
                                        case "BLUE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
                                            break;
                                    }
                                    cell.CellStyle = cellStyle;
                                }
                            }
                        }
                        cellIndex++;
                    }
                    rowIndex++;
                }
                #endregion
                for (int i = 0; i <= table.Columns.Count; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                workbook.Write(ms);
                ms.Flush();
            }
            return ms;
        }

        #endregion

        #region DataTable导出到制定路径的Excel
        /// <summary>
        /// DataTable导出Excel
        /// </summary>
        /// <param name="table">要导出的datatable</param>
        /// <returns>内存流</returns>
        public static void RenderToExcel(DataTable table,string url)
        {
            using (table)
            {
                #region

                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);
                IFont fontHeader = workbook.CreateFont();
                //设置格式
                fontHeader.FontHeightInPoints = 10;
                fontHeader.FontName = "微软雅黑";
                fontHeader.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                ICellStyle headerStyle = workbook.CreateCellStyle();
                headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
                headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                headerStyle.SetFont(fontHeader);

                //读取datatable列，填充到EXCEL
                foreach (DataColumn column in table.Columns)
                {
                    ICell cell = headerRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(column.Caption);
                    cell.CellStyle = headerStyle;
                }
                int rowIndex = 1;
                //循环每一行数据
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (DataColumn column in table.Columns)
                    {
                        ICell cell = dataRow.CreateCell(column.Ordinal);
                        cell.SetCellValue(row[column].ToString());
                        if (table.Columns.Contains("ISSTYLE"))
                        {
                            string MsIndex = table.Rows[rowIndex - 1]["ISSTYLE"].ToString();
                            if (string.IsNullOrEmpty(MsIndex))
                            {
                                continue;
                            }
                            string[] str = MsIndex.Split(',');
                            foreach (string item in str)
                            {
                                string[] strIndex = item.Split(':');
                                if (Convert.ToInt32(strIndex[0]) == cellIndex)
                                {
                                    ICellStyle cellStyle = workbook.CreateCellStyle();
                                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                                    IFont font = workbook.CreateFont();
                                    font.FontHeightInPoints = 10;
                                    font.FontName = "微软雅黑";
                                    if (table.Columns.Contains("FONTBOLD") && (row["FONTBOLD"].ToString() == "1"))
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                                    }
                                    else
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
                                    }
                                    cellStyle.SetFont(font);
                                    switch (strIndex[1])
                                    {
                                        case "RED":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
                                            break;
                                        case "WHITE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            break;
                                        case "BLACK":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            break;
                                        case "GREEN":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                                            break;
                                        case "BLUE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
                                            break;
                                    }
                                    cell.CellStyle = cellStyle;
                                }
                            }
                        }
                        cellIndex++;
                    }
                    rowIndex++;
                }
                #endregion
                for (int i = 0; i <= table.Columns.Count; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                FileStream file = new FileStream(url, FileMode.OpenOrCreate);
                workbook.Write(file);
                file.Close();

            }
        }

        #endregion

        #region DataTable导出到制定路径的Excel(修改标题)
        /// <summary>
        /// DataTable导出Excel
        /// </summary>
        /// <param name="table">要导出的datatable</param>
        /// <returns>内存流</returns>
        public static void RenderToExcel(DataTable table, string url, Dictionary<string, string> mapField)
        {
            using (table)
            {
                #region

                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);
                IFont fontHeader = workbook.CreateFont();
                //设置格式
                fontHeader.FontHeightInPoints = 10;
                fontHeader.FontName = "微软雅黑";
                fontHeader.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                ICellStyle headerStyle = workbook.CreateCellStyle();
                headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
                headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                headerStyle.SetFont(fontHeader);

                //读取datatable列，填充到EXCEL
                foreach (DataColumn column in table.Columns)
                {
                    string columnName = column.Caption;
                    if (mapField.Keys.Contains(column.Caption))
                    {
                        columnName = mapField[column.Caption];
                    }

                    ICell cell = headerRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(columnName);
                    cell.CellStyle = headerStyle;
                }
                int rowIndex = 1;
                //循环每一行数据
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (DataColumn column in table.Columns)
                    {
                        ICell cell = dataRow.CreateCell(column.Ordinal);
                        cell.SetCellValue(row[column].ToString());
                        if (table.Columns.Contains("ISSTYLE"))
                        {
                            string MsIndex = table.Rows[rowIndex - 1]["ISSTYLE"].ToString();
                            if (string.IsNullOrEmpty(MsIndex))
                            {
                                continue;
                            }
                            string[] str = MsIndex.Split(',');
                            foreach (string item in str)
                            {
                                string[] strIndex = item.Split(':');
                                if (Convert.ToInt32(strIndex[0]) == cellIndex)
                                {
                                    ICellStyle cellStyle = workbook.CreateCellStyle();
                                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                                    IFont font = workbook.CreateFont();
                                    font.FontHeightInPoints = 10;
                                    font.FontName = "微软雅黑";
                                    if (table.Columns.Contains("FONTBOLD") && (row["FONTBOLD"].ToString() == "1"))
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                                    }
                                    else
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
                                    }
                                    cellStyle.SetFont(font);
                                    switch (strIndex[1])
                                    {
                                        case "RED":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
                                            break;
                                        case "WHITE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            break;
                                        case "BLACK":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            break;
                                        case "GREEN":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                                            break;
                                        case "BLUE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
                                            break;
                                    }
                                    cell.CellStyle = cellStyle;
                                }
                            }
                        }
                        cellIndex++;
                    }
                    rowIndex++;
                }
                #endregion
                for (int i = 0; i <= table.Columns.Count; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                FileStream file = new FileStream(url, FileMode.OpenOrCreate);
                workbook.Write(file);
                file.Close();
            }
        }

        #endregion



        #region DataTable导出Excel
        /// <summary>
        /// DataTable导出Excel
        /// </summary>
        /// <param name="table">要导出的datatable</param>
        /// <returns>内存流</returns>
        public static MemoryStream RenderToExcel(DataTable table,Dictionary<string,string> mapField)
        {
            MemoryStream ms = new MemoryStream();

            using (table)
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);
                IFont fontHeader = workbook.CreateFont();
                //设置格式
                fontHeader.FontHeightInPoints = 10;
                fontHeader.FontName = "微软雅黑";
                fontHeader.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                ICellStyle headerStyle = workbook.CreateCellStyle();
                headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
                headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                headerStyle.SetFont(fontHeader);

                //读取datatable列，填充到EXCEL
                foreach (DataColumn column in table.Columns)
                {
                    string columnName = column.Caption;
                    if(mapField.Keys.Contains(column.Caption))
                    {
                        columnName = mapField[column.Caption];
                    }

                    ICell cell = headerRow.CreateCell(column.Ordinal);
                    cell.SetCellValue(columnName);
                    cell.CellStyle = headerStyle;
                }
                int rowIndex = 1;
                //循环每一行数据
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (DataColumn column in table.Columns)
                    {
                        ICell cell = dataRow.CreateCell(column.Ordinal);
                        cell.SetCellValue(row[column].ToString());
                        if (table.Columns.Contains("ISSTYLE"))
                        {
                            string MsIndex = table.Rows[rowIndex - 1]["ISSTYLE"].ToString();
                            if (string.IsNullOrEmpty(MsIndex))
                            {
                                continue;
                            }
                            string[] str = MsIndex.Split(',');
                            foreach (string item in str)
                            {
                                string[] strIndex = item.Split(':');
                                if (Convert.ToInt32(strIndex[0]) == cellIndex)
                                {
                                    ICellStyle cellStyle = workbook.CreateCellStyle();
                                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                                    cellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                                    IFont font = workbook.CreateFont();
                                    font.FontHeightInPoints = 10;
                                    font.FontName = "微软雅黑";
                                    if (table.Columns.Contains("FONTBOLD") && (row["FONTBOLD"].ToString() == "1"))
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                                    }
                                    else
                                    {
                                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
                                    }
                                    cellStyle.SetFont(font);
                                    switch (strIndex[1])
                                    {
                                        case "RED":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
                                            break;
                                        case "WHITE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            break;
                                        case "BLACK":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                                            break;
                                        case "GREEN":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                                            break;
                                        case "BLUE":
                                            font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
                                            break;
                                    }
                                    cell.CellStyle = cellStyle;
                                }
                            }
                        }
                        cellIndex++;
                    }
                    rowIndex++;
                }
                for (int i = 0; i <= table.Columns.Count; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                workbook.Write(ms);
                ms.Flush();
            }
            return ms;
        }
        #endregion

        #region DataSet导出EXCEL
        /// <summary>
        /// DataSet导出EXCEL
        /// </summary>
        /// <param name="ds">要导出的EXCEL</param>
        /// <returns>内存流</returns>
        public static MemoryStream RenderDataSetToExcel(DataSet ds)
        {
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new XSSFWorkbook();
            for (int k = 0; k < ds.Tables.Count; k++)
            {
                var table = ds.Tables[k];
                #region
                using (table)
                {
                    ISheet sheet = workbook.CreateSheet(table.TableName);

                    IRow headerRow = sheet.CreateRow(0);

                    IFont fontHeader = workbook.CreateFont();
                    fontHeader.FontHeightInPoints = 10;
                    fontHeader.FontName = "微软雅黑";
                    fontHeader.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                    ICellStyle headerStyle = workbook.CreateCellStyle();
                    headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    headerStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
                    headerStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                    headerStyle.SetFont(fontHeader);
                    foreach (DataColumn column in table.Columns)
                    {
                        ICell cell = headerRow.CreateCell(column.Ordinal);
                        cell.SetCellValue(column.Caption);
                        cell.CellStyle = headerStyle;

                    }
                    int rowIndex = 1;
                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        int cellIndex = 0;
                        foreach (DataColumn column in table.Columns)
                        {

                            ICell cell = dataRow.CreateCell(column.Ordinal);
                            cell.SetCellValue(row[column].ToString());
                            if (table.Columns.Contains("ISSTYLE"))
                            {
                                string MsIndex = table.Rows[rowIndex - 1]["ISSTYLE"].ToString();
                                if (string.IsNullOrEmpty(MsIndex))
                                {
                                    continue;
                                }
                                string[] str = MsIndex.Split(',');
                                foreach (string item in str)
                                {
                                    string[] strIndex = item.Split(':');
                                    if (Convert.ToInt32(strIndex[0]) == cellIndex)
                                    {
                                        ICellStyle cellStyle = workbook.CreateCellStyle();
                                        cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                                        cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                                        cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                                        cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                                        cellStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
                                        IFont font = workbook.CreateFont();
                                        font.FontHeightInPoints = 10;
                                        font.FontName = "微软雅黑";
                                        if (table.Columns.Contains("FONTBOLD") && (row["FONTBOLD"].ToString() == "1"))
                                        {
                                            font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                                        }
                                        else
                                        {
                                            font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Normal;
                                        }
                                        cellStyle.SetFont(font);
                                        switch (strIndex[1])
                                        {
                                            case "RED":
                                                font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
                                                cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
                                                break;
                                            case "WHITE":
                                                font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
                                                cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                                break;
                                            case "BLACK":
                                                font.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;
                                                cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.White.Index;
                                                break;
                                            case "GREEN":
                                                font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
                                                cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
                                                break;
                                            case "BLUE":
                                                font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                                                cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
                                                break;
                                        }
                                        cell.CellStyle = cellStyle;
                                    }
                                }
                            }
                            cellIndex++;
                        }

                        rowIndex++;
                    }
                    for (int i = 0; i <= table.Columns.Count; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }
                }
                #endregion
            }
            workbook.Write(ms);
            ms.Flush();
            return ms;
        }
        #endregion

        #region 导入Excel字符流成DataTable
        /// <summary>
        /// 导入Excel字符流成DataTable
        /// </summary>
        /// <param name="excelFileStream">excel字符流</param>
        /// <returns>返回DataTable</returns>
        public DataTable RenderFromExcel(Stream excelFileStream)
        {
            using (excelFileStream)
            {
                IWorkbook workbook = null;
                workbook = new HSSFWorkbook(excelFileStream);

                ISheet sheet = workbook.GetSheetAt(0); //取第一个表
                {
                    DataTable table = new DataTable();

                    IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                    //handling header.
                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
                        table.Columns.Add(column);
                    }

                    for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dataRow = table.NewRow();

                        if (row != null)
                        {
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    if (row.GetCell(j).CellType == CellType.Numeric)
                                        dataRow[j] = row.GetCell(j).NumericCellValue;
                                    else if (row.GetCell(j).CellType == CellType.String)
                                        dataRow[j] = row.GetCell(j).StringCellValue;
                                }
                            }
                        }

                        table.Rows.Add(dataRow);
                    }
                    return table;
                }
            }
        }
        #endregion

        #region 导入Excel字符流成DataSet
        /// <summary>
        /// 导入Excel字符流成DataSet
        /// </summary>
        /// <param name="excelFileStream">excel字符流</param>
        /// <returns>返回DataSet</returns>
        public DataSet RenderFromExcelToDataSet(Stream excelFileStream)
        {
            using (excelFileStream)
            {
                DataSet ds = new DataSet();
                IWorkbook workbook = null;
                workbook = new HSSFWorkbook(excelFileStream);
                for (int n = 0; n < workbook.NumberOfSheets; n++)
                {
                    ISheet sheet = workbook.GetSheetAt(n); //取第一个表
                    {
                        DataTable table = new DataTable();

                        IRow headerRow = sheet.GetRow(0);//第一行为标题行
                        int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                        int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                        //handling header.
                        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
                            table.Columns.Add(column);
                        }

                        for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                        {
                            IRow row = sheet.GetRow(i);
                            DataRow dataRow = table.NewRow();

                            if (row != null)
                            {
                                for (int j = row.FirstCellNum; j < cellCount; j++)
                                {
                                    if (row.GetCell(j) != null)
                                    {
                                        if (row.GetCell(j).CellType == CellType.Numeric)
                                            dataRow[j] = row.GetCell(j).NumericCellValue;
                                        else if (row.GetCell(j).CellType == CellType.String)
                                            dataRow[j] = row.GetCell(j).StringCellValue;
                                    }
                                }
                            }

                            table.Rows.Add(dataRow);
                        }
                        ds.Tables.Add(table);
                    }
                }

                return ds;
            }
        }
        #endregion

        #region 导入Excel(指定路径方式)
        /// <summary>
        /// 导入Excel(指定路径方式)
        /// </summary>
        /// <param name="fullPath">文件完整的绝对路径</param>
        /// <returns>返回DataTable</returns>
        public DataTable ImportExcelByPath(string fullPath)
        {

            DataTable dt = new DataTable();
            IWorkbook workbook = null;
            string tempPath = AppDomain.CurrentDomain.BaseDirectory + "temp.xls";
            if (File.Exists(tempPath))
            {
                File.Delete(tempPath);
            }
            File.Copy(fullPath, tempPath);
            FileStream fs = File.OpenRead(tempPath);
            try
            {
                workbook = new XSSFWorkbook(fs);
            }
            catch (Exception ex)
            {
                workbook = new HSSFWorkbook(fs);
            }
            try
            {
                ISheet sheet = workbook.GetSheetAt(0); //取第一个表
                IRow headerRow = sheet.GetRow(0);//第一行为标题行
                int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).ToString().ToUpper());
                    dt.Columns.Add(column);
                }
                for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = dt.NewRow();
                    if (row != null)
                    {
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            if (row.GetCell(j) != null)
                            {
                                if (row.GetCell(j).CellType == CellType.Numeric)
                                {
                                    short format = row.GetCell(j).CellStyle.DataFormat;
                                    if (format != 0) { dataRow[j] = row.GetCell(j).DateCellValue.ToString("yyyy-MM-dd"); } else { dataRow[j] = row.GetCell(j).NumericCellValue; }
                                }
                                else if (row.GetCell(j).CellType == CellType.String)
                                    dataRow[j] = row.GetCell(j).StringCellValue;
                            }
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
                fs.Close();
                File.Delete(tempPath);
            }
            catch(Exception ex)
            {
                fs.Close();
                File.Delete(tempPath);
            }
            return dt;
        }
        #endregion

        #region 导入Excel(指定路径方式)  支持多个工作表
        /// <summary>
        /// 导入Excel(指定路径方式) 支持多个工作表
        /// </summary>
        /// <param name="fullPath">文件完整的绝对路径</param>
        /// <param name="num">要读取工作表个数</param>
        /// <returns>返回DataSet</returns>
        public DataSet ImportExcelByPathToDataSet(string fullPath, int sheetnum)
        {

            DataSet ds = new DataSet();
            IWorkbook workbook = null;
            string tempname = "/" + Guid.NewGuid().ToString() + ".xls";
            string tempPath = AppDomain.CurrentDomain.BaseDirectory + tempname;
            File.Copy(fullPath, tempPath, true);
            FileStream fs = File.Open(tempPath, FileMode.Open);
            try
            {
                workbook = new XSSFWorkbook(fs);
            }
            catch (Exception ex)
            {
                workbook = new HSSFWorkbook(fs);
            }
            try
            {
                //取指定个数工作表
                for (int a = 0; a < sheetnum; a++)
                {
                    DataTable dt = new DataTable();

                    ISheet sheet = workbook.GetSheetAt(a);
                    dt.TableName = sheet.SheetName;
                    int count = sheet.FirstRowNum;

                    IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    if (headerRow != null)
                    {
                        int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                        int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(headerRow.GetCell(i).ToString().ToUpper());
                            dt.Columns.Add(column);
                        }

                        for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                        {
                            IRow row = sheet.GetRow(i);
                            DataRow dataRow = dt.NewRow();

                            if (row != null)
                            {
                                for (int j = row.FirstCellNum; j < cellCount; j++)
                                {
                                    if (row.GetCell(j) != null)
                                    {
                                        if (row.GetCell(j).CellType == CellType.Numeric)
                                            dataRow[j] = row.GetCell(j).NumericCellValue;
                                        else if (row.GetCell(j).CellType == CellType.String)
                                            dataRow[j] = row.GetCell(j).StringCellValue;
                                    }
                                }
                            }
                            dt.Rows.Add(dataRow);
                        }
                        //dt.TableName = "Table" + (a + 1).ToString();
                        ds.Tables.Add(dt);
                    }

                }
                fs.Close();
                File.Delete(tempPath);
            }
            catch
            {
                fs.Close();
                File.Delete(tempPath);
            }
            return ds;
        }
        #endregion
    }

    /// <summary>
    /// 合并列
    /// </summary>
    public class MergedCells
    {
        /// <summary>
        /// 列名
        /// </summary>
        public string ColumnName
        {
            get;
            set;
        }

        /// <summary>
        /// 开始行号
        /// </summary>
        public int BeginRow
        {
            get;
            set;
        }
        /// <summary>
        /// 结束行号
        /// </summary>
        public int EndRow
        {
            get;
            set;
        }
        /// <summary>
        /// 开始列
        /// </summary>
        public int BeginColumn
        {
            get;
            set;
        }
        /// <summary>
        /// 结束列
        /// </summary>
        public int EndColumn
        {
            get;
            set;
        }
    }
}
