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

namespace CallCenter.Utility
{
    public class NPOIHelper
    {
        private string _title;
        private string _sheetName;
        private string _filePath;

        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public bool ToExcel(DataTable table, string[] columns = null)
        {
            FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            IWorkbook workBook = new HSSFWorkbook();
            if (string.IsNullOrWhiteSpace(this._sheetName))
            {
                this._sheetName = "sheet1";
            }

            ISheet sheet = workBook.CreateSheet(this._sheetName);

            //处理表格标题
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue(this._title);
            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
            row.Height = 500;

            ICellStyle cellStyle = workBook.CreateCellStyle();
            IFont font = workBook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 17;
            cellStyle.SetFont(font);
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.Alignment = HorizontalAlignment.Center;
            row.Cells[0].CellStyle = cellStyle;

            //处理表格列头
            row = sheet.CreateRow(1);
            if (columns == null)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
                    row.Height = 350;
                    sheet.AutoSizeColumn(i);
                }
            }
            else
            {
                for (int i = 0; i < columns.Length; i++)
                {
                    row.CreateCell(i).SetCellValue(columns[i]);
                    row.Height = 350;
                    sheet.AutoSizeColumn(i);
                }
            }




            //处理数据内容
            for (int i = 0; i < table.Rows.Count; i++)
            {
                row = sheet.CreateRow(2 + i);
                row.Height = 250;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
                    sheet.SetColumnWidth(j, 256 * 15);
                }
            }

            //写入数据流
            workBook.Write(fs);
            fs.Flush();
            fs.Close();

            return true;
        }

        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="table"></param>
        /// <param name="title"></param>
        /// <param name="sheetName">空字符串或null的话默认sheet1</param>
        /// <param name="columns">自定义表格列头，默认null</param>
        /// <returns></returns>
        public bool ToExcel(DataTable table, string title, string sheetName, string filePath, string[] columns = null)
        {
            this._title = title;
            this._sheetName = sheetName;
            this._filePath = filePath;
            return ToExcel(table, columns);
        }

        /// <summary>
        /// 弹出下载框导出excel
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ExportToExcelSplitSheet(string Name, DataTable dt, string[] cols = null)
        {
            //try
            //{
            //if (dt.Rows.Count > 0)
            //{
            HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
                                                       //IWorkbook workbook = new XSSFWorkbook();//导出xlsx
            int SheetNum = 1;
            ISheet sheet = workbook.CreateSheet("Sheet" + SheetNum);

            ICellStyle HeadercellStyle = workbook.CreateCellStyle();
            HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            HeadercellStyle.Alignment = HorizontalAlignment.Center;
            HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
            HeadercellStyle.FillPattern = FillPattern.SolidForeground;
            HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;

            //字体
            NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
            headerfont.Boldweight = (short)FontBoldWeight.Bold;
            headerfont.FontHeightInPoints = 12;
            HeadercellStyle.SetFont(headerfont);


            //用column name 作为列名
            int icolIndex = 0;
            IRow headerRow = sheet.CreateRow(0);
            if (cols == null || (cols != null && cols.Length == 0))
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    ICell cell = headerRow.CreateCell(icolIndex);
                    cell.SetCellValue(dc.ColumnName);
                    cell.CellStyle = HeadercellStyle;
                    icolIndex++;
                }
            }
            else
            {
                foreach (string dc in cols)
                {
                    ICell cell = headerRow.CreateCell(icolIndex);
                    cell.SetCellValue(dc);
                    cell.CellStyle = HeadercellStyle;
                    icolIndex++;
                }
            }
            ICellStyle cellStyle = workbook.CreateCellStyle();

            //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


            NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
            cellfont.Boldweight = (short)FontBoldWeight.Normal;
            cellStyle.SetFont(cellfont);

            //建立内容行
            int iRowIndex = 0;
            int iRowIndex2 = 0;
            foreach (DataRow dr in dt.Rows)
            {
                int iCellIndex = 0;
                IRow irow = sheet.CreateRow(iRowIndex + 1);
                if (iRowIndex < 60000)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string strsj = string.Empty;
                        if (dr[i] != null)
                        {
                            strsj = dr[i].ToString();
                        }
                        ICell cell = irow.CreateCell(iCellIndex);
                        cell.SetCellValue(strsj);
                        cell.CellStyle = cellStyle;
                        iCellIndex++;
                    }
                    iRowIndex++;
                }

                int iCellIndex2 = 0;
                SheetNum = SheetNum + 1;
                ISheet sheet2 = workbook.CreateSheet("Sheet" + SheetNum);
                if (iRowIndex >= 60000)
                {

                    if (iRowIndex == 60000)
                    {

                        int icolIndex2 = 0;
                        foreach (string dc in cols)
                        {
                            ICell cell = headerRow.CreateCell(icolIndex2);
                            cell.SetCellValue(dc);
                            cell.CellStyle = HeadercellStyle;
                            icolIndex2++;
                        }
                    }

                    IRow irow2 = sheet2.CreateRow(iRowIndex2 + 1);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string strsj = string.Empty;
                        if (dr[i] != null)
                        {
                            strsj = dr[i].ToString();
                        }
                        ICell cell = irow.CreateCell(iCellIndex2);
                        cell.SetCellValue(strsj);
                        cell.CellStyle = cellStyle;
                        iCellIndex2++;
                    }
                    iRowIndex++;
                    iRowIndex2++;
                }

            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);

                HttpContext curContext = HttpContext.Current;


                // 设置编码和附件格式
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = Encoding.UTF8;//Encoding.UTF8;
                curContext.Response.Charset = "";
                curContext.Response.AppendHeader("Content-Disposition",
                    "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));

                curContext.Response.BinaryWrite(ms.GetBuffer());

                workbook = null;
                ms.Close();
                ms.Dispose();

                curContext.Response.End();
            }

            return "";
            //}
            //catch(Exception e)
            //{
            //    string estr = e.Message;
            //    return "导出失败！";
            //}
        }


        public string ExportToExcel(string Name, DataTable dt, string[] cols = null)
        {
            try
            {
                //if (dt.Rows.Count > 0)
                //{
                HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
                //IWorkbook workbook = new XSSFWorkbook();//导出xlsx
                ISheet sheet = workbook.CreateSheet("Sheet1");

                ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.Alignment = HorizontalAlignment.Center;
                HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
                HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;

                //字体
                NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
                headerfont.Boldweight = (short)FontBoldWeight.Bold;
                headerfont.FontHeightInPoints = 12;
                HeadercellStyle.SetFont(headerfont);


                //用column name 作为列名
                int icolIndex = 0;
                IRow headerRow = sheet.CreateRow(0);
                if (cols == null || (cols != null && cols.Length == 0))
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc.ColumnName);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                else
                {
                    foreach (string dc in cols)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


                NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
                cellfont.Boldweight = (short)FontBoldWeight.Normal;
                cellStyle.SetFont(cellfont);

                //建立内容行
                int iRowIndex = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    int iCellIndex = 0;
                    IRow irow = sheet.CreateRow(iRowIndex + 1);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string strsj = string.Empty;
                        if (dr[i] != null)
                        {
                            strsj = dr[i].ToString();
                        }
                        ICell cell = irow.CreateCell(iCellIndex);
                        cell.SetCellValue(strsj);
                        cell.CellStyle = cellStyle;
                        iCellIndex++;
                    }
                    iRowIndex++;
                }

                ////自适应列宽度
                //for (int i = 0; i < icolIndex; i++)
                //{
                //    sheet.AutoSizeColumn(i);
                //}

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);

                    HttpContext curContext = HttpContext.Current;


                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;//Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));

                    curContext.Response.BinaryWrite(ms.GetBuffer());

                    workbook = null;
                    ms.Close();
                    ms.Dispose();

                    curContext.Response.End();
                }
                //}
                return "";
            }
            catch
            {
                return "导出失败！";
            }
        }


        /// <summary>
        /// 导入excel转换为datatable
        /// </summary>
        /// <param name="upfile"></param>
        /// <param name="headrow"></param>
        /// <returns></returns>
        public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
        {
            DataTable dt = new DataTable();

            IWorkbook workbook = null;

            Stream stream = upfile.InputStream;

            string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
            if (suffix == "xlsx") // 2007版本
            {
                workbook = new XSSFWorkbook(stream);
            }
            else if (suffix == "xls") // 2003版本
            {
                workbook = new HSSFWorkbook(stream);
            }

            //获取excel的第一个sheet
            ISheet sheet = workbook.GetSheetAt(0);

            //获取sheet的第一行
            IRow headerRow = sheet.GetRow(headrow);

            //一行最后一个方格的编号 即总的列数
            int cellCount = headerRow.LastCellNum;
            //最后一列的标号  即总的行数
            int rowCount = sheet.LastRowNum;
            //列名
            for (int i = 0; i < cellCount; i++)
            {
                dt.Columns.Add(headerRow.GetCell(i).ToString());
            }

            for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
            {
                DataRow dr = dt.NewRow();

                IRow row = sheet.GetRow(i);
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dr[j] = row.GetCell(j).ToString();
                    }
                }

                dt.Rows.Add(dr);
            }

            sheet = null;
            workbook = null;

            return dt;
        }

        /// <summary>
        /// 导入excel转换为datatable
        /// </summary>
        /// <param name="upfile"></param>
        /// <param name="headrow"></param>
        /// <returns></returns>
        public DataTable ExcelToTable(string fileName, int headrow)
        {
            DataTable dt = new DataTable();

            IWorkbook workbook = null;

            Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);

            string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
            if (suffix == "xlsx") // 2007版本
            {
                workbook = new XSSFWorkbook(stream);
            }
            else if (suffix == "xls") // 2003版本
            {
                workbook = new HSSFWorkbook(stream);
            }

            //获取excel的第一个sheet
            ISheet sheet = workbook.GetSheetAt(0);

            //获取sheet的第一行
            IRow headerRow = sheet.GetRow(headrow);

            //一行最后一个方格的编号 即总的列数
            int cellCount = headerRow.LastCellNum;
            //最后一列的标号  即总的行数
            int rowCount = sheet.LastRowNum;
            //列名
            for (int i = 0; i < cellCount; i++)
            {
                dt.Columns.Add(headerRow.GetCell(i).ToString());
            }

            for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
            {
                DataRow dr = dt.NewRow();

                IRow row = sheet.GetRow(i);
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dr[j] = row.GetCell(j).ToString();
                    }
                }

                dt.Rows.Add(dr);
            }

            sheet = null;
            workbook = null;

            return dt;
        }

        //2017-11-11数据第一行为标题
        #region
        /// <summary>
        /// 弹出下载框导出excel（数据第一行为标题）
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ExportToExcel2(string Name, DataTable dt, string[] cols = null)
        {
            try
            {
                //if (dt.Rows.Count > 0)
                //{
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");

                ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                HeadercellStyle.Alignment = HorizontalAlignment.Center;
                HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
                HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;

                //字体
                NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
                headerfont.Boldweight = (short)FontBoldWeight.Bold;
                headerfont.FontHeightInPoints = 12;
                HeadercellStyle.SetFont(headerfont);

                //第一行为标题
                IRow headRow = sheet.CreateRow(0);
                ICell cellh = headRow.CreateCell(0);
                cellh.CellStyle = HeadercellStyle;
                cellh.SetCellValue(Name);
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));


                //用column name 作为列名
                int icolIndex = 0;
                IRow headerRow = sheet.CreateRow(1);
                if (cols == null || (cols != null && cols.Length == 0))
                {
                    //foreach (DataColumn dc in dt.Columns)
                    //{
                    //    ICell cell = headerRow.CreateCell(icolIndex);
                    //    cell.SetCellValue(dc.ColumnName);
                    //    cell.CellStyle = HeadercellStyle;
                    //    icolIndex++;
                    //}
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dt.Columns[i].ColumnName);//cell.SetCellValue(dt.Rows [0][i].ToString());
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                else
                {
                    foreach (string dc in cols)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


                NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
                cellfont.Boldweight = (short)FontBoldWeight.Normal;
                cellStyle.SetFont(cellfont);

                //建立内容行
                int iRowIndex = 2;
                foreach (DataRow dr in dt.Rows)
                {
                    if (iRowIndex >= 2)
                    {


                        int iCellIndex = 0;
                        IRow irow = sheet.CreateRow(iRowIndex);
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            string strsj = string.Empty;
                            if (dr[i] != null)
                            {
                                strsj = dr[i].ToString();
                            }
                            ICell cell = irow.CreateCell(iCellIndex);
                            cell.SetCellValue(strsj);
                            cell.CellStyle = cellStyle;
                            iCellIndex++;
                        }
                    }
                    iRowIndex++;
                }

                //自适应列宽度
                for (int i = 0; i < icolIndex; i++)
                {
                    sheet.AutoSizeColumn(i);
                    // 解决自动设置列宽中文失效的问题
                    sheet.SetColumnWidth(i, sheet.GetColumnWidth(i) * 17 / 10);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);

                    HttpContext curContext = HttpContext.Current;


                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));

                    curContext.Response.BinaryWrite(ms.GetBuffer());

                    workbook = null;
                    ms.Close();
                    ms.Dispose();

                    curContext.Response.End();
                }
                //}
                return "";
            }
            catch
            {
                return "导出失败！";
            }
        }
        #endregion

        public string ExportToExcel2003(string Name, DataTable dt, string[] cols = null)
        {
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                HeadercellStyle.BorderBottom = BorderStyle.Thin;
                HeadercellStyle.BorderLeft = BorderStyle.Thin;
                HeadercellStyle.BorderRight = BorderStyle.Thin;
                HeadercellStyle.BorderTop = BorderStyle.Thin;
                HeadercellStyle.Alignment = HorizontalAlignment.Center;
                HeadercellStyle.FillForegroundColor = HSSFColor.SkyBlue.Index;
                HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                HeadercellStyle.FillBackgroundColor = HSSFColor.SkyBlue.Index;

                //字体
                IFont headerfont = workbook.CreateFont();
                headerfont.Boldweight = (short)FontBoldWeight.Bold;
                headerfont.FontHeightInPoints = 12;
                HeadercellStyle.SetFont(headerfont);


                //用column name 作为列名
                int icolIndex = 0;
                //建立内容行
                int iRowIndex = 0;

                int sheetCount = 0;
                int sheetRowCount = 60000;
                ISheet sheet = null;
                IRow headerRow = null;

                if (dt.Rows.Count == 0)
                {
                    sheet = workbook.CreateSheet(Name);
                    headerRow = sheet.CreateRow(0);

                    #region 表头
                    if (cols == null || (cols != null && cols.Length == 0))
                    {
                        foreach (DataColumn dc in dt.Columns)
                        {
                            ICell cell = headerRow.CreateCell(icolIndex);
                            cell.SetCellValue(dc.ColumnName);
                            cell.CellStyle = HeadercellStyle;
                            icolIndex++;
                        }
                    }
                    else
                    {
                        foreach (string dc in cols)
                        {
                            ICell cell = headerRow.CreateCell(icolIndex);
                            cell.SetCellValue(dc);
                            cell.CellStyle = HeadercellStyle;
                            icolIndex++;
                        }
                    }
                    #endregion
                }
                else
                {
                    ICellStyle cellStyle = workbook.CreateCellStyle();

                    //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                    cellStyle.BorderBottom = BorderStyle.Thin;
                    cellStyle.BorderLeft = BorderStyle.Thin;
                    cellStyle.BorderRight = BorderStyle.Thin;
                    cellStyle.BorderTop = BorderStyle.Thin;
                    IFont cellfont = workbook.CreateFont();
                    cellfont.Boldweight = (short)FontBoldWeight.Normal;
                    cellStyle.SetFont(cellfont);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (i % sheetRowCount == 0)
                        {
                            if (i > 0)
                            {
                                //自适应列宽度
                                for (int j = 0; j < icolIndex; j++)
                                {
                                    sheet.AutoSizeColumn(j);
                                }
                            }

                            sheetCount++;
                            iRowIndex = 0;
                            icolIndex = 0;

                            sheet = workbook.CreateSheet(Name + sheetCount.ToString());
                            headerRow = sheet.CreateRow(0);

                            #region 表头
                            if (cols == null || (cols != null && cols.Length == 0))
                            {
                                foreach (DataColumn dc in dt.Columns)
                                {
                                    ICell cell = headerRow.CreateCell(icolIndex);
                                    cell.SetCellValue(dc.ColumnName);
                                    cell.CellStyle = HeadercellStyle;
                                    icolIndex++;
                                }
                            }
                            else
                            {
                                foreach (string dc in cols)
                                {
                                    ICell cell = headerRow.CreateCell(icolIndex);
                                    cell.SetCellValue(dc);
                                    cell.CellStyle = HeadercellStyle;
                                    icolIndex++;
                                }
                            }
                            #endregion
                        }

                        IRow irow = sheet.CreateRow(iRowIndex + 1);
                        foreach (DataColumn dc in dt.Columns)
                        {
                            string strsj = dt.Rows[i][dc]?.ToString() ?? "";
                            ICell cell = irow.CreateCell(dc.Ordinal);
                            cell.SetCellValue(strsj);
                            cell.CellStyle = cellStyle;
                        }
                        iRowIndex++;
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    HttpContext curContext = HttpContext.Current;
                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
                    curContext.Response.AppendHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xls", Encoding.UTF8));
                    curContext.Response.BinaryWrite(ms.GetBuffer());
                    workbook = null;
                    ms.Close();
                    ms.Dispose();
                    curContext.Response.End();
                }

                return "";
            }
            catch (Exception ex)
            {
                // LogHelper.Error("导出2003失败！", ex);
                return "导出失败！";
            }
        }


        /// <summary>
        /// 弹出下载框导出excel
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ExportToExcel2007(string Name, DataTable dt, string[] cols = null)
        {
            try
            {
                //if (dt.Rows.Count > 0)
                //{

                XSSFWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet(Name);

                ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                HeadercellStyle.BorderBottom = BorderStyle.Thin;
                HeadercellStyle.BorderLeft = BorderStyle.Thin;
                HeadercellStyle.BorderRight = BorderStyle.Thin;
                HeadercellStyle.BorderTop = BorderStyle.Thin;
                HeadercellStyle.Alignment = HorizontalAlignment.Center;
                HeadercellStyle.FillForegroundColor = HSSFColor.SkyBlue.Index;
                HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                HeadercellStyle.FillBackgroundColor = HSSFColor.SkyBlue.Index;

                //字体
                IFont headerfont = workbook.CreateFont();
                headerfont.Boldweight = (short)FontBoldWeight.Bold;
                headerfont.FontHeightInPoints = 12;
                HeadercellStyle.SetFont(headerfont);


                //用column name 作为列名
                int icolIndex = 0;
                IRow headerRow = sheet.CreateRow(0);

                if (cols == null || (cols != null && cols.Length == 0))
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc.ColumnName);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                else
                {
                    foreach (string dc in cols)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }
                }
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                cellStyle.BorderBottom = BorderStyle.Thin;
                cellStyle.BorderLeft = BorderStyle.Thin;
                cellStyle.BorderRight = BorderStyle.Thin;
                cellStyle.BorderTop = BorderStyle.Thin;


                IFont cellfont = workbook.CreateFont();
                cellfont.Boldweight = (short)FontBoldWeight.Normal;
                cellStyle.SetFont(cellfont);

                //建立内容行
                int iRowIndex = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    int iCellIndex = 0;
                    IRow irow = sheet.CreateRow(iRowIndex + 1);

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string strsj = string.Empty;
                        if (dr[i] != null)
                        {
                            strsj = dr[i].ToString();
                        }
                        ICell cell = irow.CreateCell(iCellIndex);
                        cell.SetCellValue(strsj);
                        cell.CellStyle = cellStyle;
                        iCellIndex++;
                    }
                    iRowIndex++;
                }

                //自适应列宽度
                for (int i = 0; i < icolIndex; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                HttpContext curContext = HttpContext.Current;
                curContext.Response.Charset = "UTF8";
                curContext.Response.ContentEncoding = Encoding.UTF8;
                curContext.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
                // 添加头信息，为"文件下载/另存为"对话框指定默认文件名
                curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xlsx", Encoding.UTF8));
                // 指定返回的是一个不能被客户端读取的流，必须被下载
                curContext.Response.ContentType = "application/ms-Excel";
                // 把文件流发送到客户端
                workbook.Write(curContext.Response.OutputStream);
                // 停止页面的执行
                curContext.Response.End();

                //}
                return "";
            }
            catch (Exception ex)
            {
                //  LogHelper.Error("导出2007失败！", ex);
                return "导出失败！";
            }
        }
    }
}
