using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NFine.Code.Excel;
using Aspose.Cells;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HPSF;
using System.Drawing;
using NPOI.XSSF.UserModel;

namespace NFine.Code
{
    public class ExcelHelper
    {
        /// <summary>
        /// 导出数据到EXCEL文件
        /// </summary>
        /// <param name="page">页面</param>
        /// <param name="gvExcel">导出的GrivView</param>
        public static void ExportToExcel(System.Web.UI.Page page, GridView dgExcel, HttpResponse Response, string fileName)
        {
            try
            {
                fileName = fileName + ".xls";
                page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "utf-8";
                Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType = "application/ms-excel";

                dgExcel.Page.EnableViewState = false;
                System.IO.StringWriter tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
                dgExcel.RenderControl(hw);

                // 输出DataGrid内容
                Response.Write(tw.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    /// <summary>
    /// 导出EXCEL
    /// </summary>
    public class GridViewExportUtil
    {
        /// <summary>
        /// 将GRIDVIEW导出excel
        /// </summary>
        /// <param name="fileName">excel文件名</param>
        /// <param name="gv">GridView ID</param>
        public static void Export(GridView gv, string PreSellNo)
        {
            //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
            List<int> list = new List<int>();
            int k = 0; //序号
            int p = 0; //价格
            int a = 0; //数量
            int d = 0; //折扣
            for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
            {
                //if (gv.HeaderRow.Cells[i].Text.Contains("F_Id") || gv.HeaderRow.Cells[i].Text.Contains("Product_Id"))
                //{
                //    list.Add(i);
                //}
                if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
                    gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)") ||
                    gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
                {
                    list.Add(i);
                }
                //if (gv.HeaderRow.Cells[i].Text.Contains("No."))
                //    k = i;
                if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
                    p = i;
                if (gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
                    a = i;
                //if (gv.HeaderRow.Cells[i].Text.Contains("Discount(%)"))
                //    d = i;
            }

            foreach (GridViewRow row in gv.Rows)
            {
                int j = 0;

                foreach (TableCell cell in row.Cells)
                {
                    if (!list.Contains(j))
                    {
                        cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
                    } // end foreach (TableCell cell in row.Cells)
                    else
                    {
                        if (j != 0)
                        {
                            if (j == p || j == a)
                                cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
                            //else if (j == d)
                            //    cell.Style.Add("vnd.ms-excel.numberformat", "#0%");
                            else
                                cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式

                        }
                    }
                    j++;
                }
            } // end foreach (GridViewRow row in dgExcel.Rows)

            HttpContext.Current.Response.Clear();
            string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
            string fileName = "";
            if (!string.IsNullOrEmpty(PreSellNo))
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-OrderNo[" + PreSellNo + "].xls";
            else
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();
                    table.GridLines = gv.GridLines;
                    if (gv.HeaderRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                        for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
                        {
                            table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
                            table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
                            table.Rows[0].Cells[i].Height = Unit.Pixel(24);
                        }
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        GridViewExportUtil.PrepareControlForExport(row);
                        row.Height = Unit.Pixel(22);
                        row.HorizontalAlign = HorizontalAlign.Center;
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    #region 手动增加头部三行和底部一行
                    #region ItemList表头行
                    table.Rows.AddAt(0, new TableRow());
                    table.Rows[0].Cells.Add(new TableCell());
                    table.Rows[0].Cells[0].Text = "ITEMS LIST";
                    table.Rows[0].Cells[0].Font.Bold = true;
                    table.Rows[0].Cells[0].ColumnSpan = 9;
                    table.Rows[0].Cells[0].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
                    table.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Black;
                    table.Rows[0].Cells[0].Height = Unit.Pixel(24);
                    table.Rows[0].Cells[0].Font.Size = FontUnit.Parse("16");
                    table.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    table.Rows[0].Cells[0].BorderWidth = 0;
                    table.Rows[0].BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
                    #endregion

                    #region To S/C No 行
                    table.Rows.AddAt(1, new TableRow());
                    table.Rows[1].Cells.Add(new TableCell());
                    table.Rows[1].Cells[0].Text = "TO:";
                    table.Rows[1].Cells[0].Font.Bold = true;
                    table.Rows[1].Cells[0].ColumnSpan = 4;
                    table.Rows[1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
                    table.Rows[1].Cells[0].BorderWidth = 0;

                    table.Rows[1].Cells.Add(new TableCell());
                    table.Rows[1].Cells[1].Text = "";
                    table.Rows[1].Cells[1].ColumnSpan = 2;
                    table.Rows[1].Cells[1].BorderWidth = 0;

                    table.Rows[1].Cells.Add(new TableCell());
                    table.Rows[1].Cells[2].Text = "S/C NO:";
                    table.Rows[1].Cells[2].Font.Bold = true;
                    table.Rows[1].Cells[2].ColumnSpan = 3;
                    table.Rows[1].Cells[2].HorizontalAlign = HorizontalAlign.Left;
                    table.Rows[1].Cells[2].BorderWidth = 0;
                    #endregion

                    #region Date 行
                    table.Rows.AddAt(2, new TableRow());
                    table.Rows[2].Cells.Add(new TableCell());
                    table.Rows[2].Cells[0].Text = "";
                    table.Rows[2].Cells[0].ColumnSpan = 4;
                    table.Rows[2].Cells[0].HorizontalAlign = HorizontalAlign.Left;
                    table.Rows[2].Cells[0].BorderWidth = 0;

                    table.Rows[2].Cells.Add(new TableCell());
                    table.Rows[2].Cells[1].Text = "";
                    table.Rows[2].Cells[1].ColumnSpan = 2;
                    table.Rows[2].Cells[1].BorderWidth = 0;

                    table.Rows[2].Cells.Add(new TableCell());
                    table.Rows[2].Cells[2].Text = "DATE:" + DateTime.Now.ToString("yyyy-MM-dd");
                    table.Rows[2].Cells[2].Font.Bold = true;
                    table.Rows[2].Cells[2].ColumnSpan = 3;
                    table.Rows[2].Cells[2].HorizontalAlign = HorizontalAlign.Left;
                    table.Rows[2].Cells[2].BorderWidth = 0;
                    #endregion

                    #region Total 行
                    table.Rows.Add(new TableRow());
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[0].Text = "Total:";
                    table.Rows[table.Rows.Count - 1].Cells[0].ColumnSpan = 2;
                    table.Rows[table.Rows.Count - 1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[1].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[2].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[3].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[4].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[5].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[6].Text = "";
                    table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
                    table.Rows[table.Rows.Count - 1].Cells[7].Text = "";
                    #endregion
                    #endregion

                    //设置table整体字体样式和大小
                    table.Font.Name = "宋体";
                    table.Font.Size = FontUnit.Parse("9.5");
                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());

                    HttpContext.Current.Response.Write(styleText);
                    HttpContext.Current.Response.End();
                }
            }
        }

        public static void Export2(GridView gv)
        {
            //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
            List<int> list = new List<int>();
            int k = 0; //序号
            int p = 0; //价格
            for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
            {
                if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
                    gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)")
                    || gv.HeaderRow.Cells[i].Text.Contains("Qty"))
                {
                    list.Add(i);
                }
                if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
                    p = i;
            }

            foreach (GridViewRow row in gv.Rows)
            {
                int j = 0;

                foreach (TableCell cell in row.Cells)
                {
                    if (!list.Contains(j))
                    {
                        cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
                    } // end foreach (TableCell cell in row.Cells)
                    else
                    {
                        if (j != 0)
                        {
                            if (j == p)
                                cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
                            else
                                cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式

                        }
                    }
                    j++;
                }
            } // end foreach (GridViewRow row in dgExcel.Rows)

            HttpContext.Current.Response.Clear();
            string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();
                    table.GridLines = gv.GridLines;
                    if (gv.HeaderRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                        for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
                        {
                            table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
                            table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
                            table.Rows[0].Cells[i].Height = Unit.Pixel(24);
                        }
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        GridViewExportUtil.PrepareControlForExport(row);
                        row.Height = Unit.Pixel(22);
                        row.HorizontalAlign = HorizontalAlign.Center;
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    //设置table整体字体样式和大小
                    table.Font.Name = "宋体";
                    table.Font.Size = FontUnit.Parse("9.5");
                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());

                    HttpContext.Current.Response.Write(styleText);
                    HttpContext.Current.Response.End();
                }
            }
        }

        public static void Export(DataTable dt, string PreSellNo)
        {
            using (GridView gv = new GridView())
            {
                DataTable dtExport = new DataTable();
                dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
                dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
                dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
                dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Discount(%)", Type.GetType("System.String"));
                dtExport.Columns.Add("Amount(USD)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Shape", Type.GetType("System.String"));
                int number = 1;
                //for (int i = 0; i < 3; i++)
                //{
                //     DataRow rtop = dtExport.NewRow();
                //     dtExport.Rows.Add(rtop);
                //}
                foreach (DataRow row in dt.Rows)
                {
                    DataRow r = dtExport.NewRow();
                    r["No."] = number;
                    r["Product No."] = row["ProductSN"].ToString();
                    r["Measurement"] = row["Measurement"].ToString();
                    r["Finished Weight(ct)"] = row["Weight"].ToString();
                    r["Rough Weight(ct)"] = row["GrossWeight"].ToString();
                    r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
                    r["Discount(%)"] = row["Discount"].ToString();
                    r["Amount(USD)"] = string.IsNullOrEmpty(row["Amount"].ToString()) ? 0 : decimal.Parse(row["Amount"].ToString());
                    r["Shape"] = row["Shape"].ToString();
                    dtExport.Rows.Add(r);
                    number++;
                }
                gv.DataSource = dtExport;
                gv.DataBind();

                Export(gv, PreSellNo);
            }
        }

        public static void Export2(DataTable dt)
        {
            using (GridView gv = new GridView())
            {
                DataTable dtExport = new DataTable();
                dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
                dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
                dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
                dtExport.Columns.Add("Sort", Type.GetType("System.String"));
                dtExport.Columns.Add("Location", Type.GetType("System.String"));
                dtExport.Columns.Add("Qty", Type.GetType("System.Int32"));
                dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
                dtExport.Columns.Add("Shape", Type.GetType("System.String"));
                dtExport.Columns.Add("CertificateNo", Type.GetType("System.String"));
                dtExport.Columns.Add("Color", Type.GetType("System.String"));
                dtExport.Columns.Add("Clarity", Type.GetType("System.String"));
                dtExport.Columns.Add("Polish", Type.GetType("System.String"));
                int number = 1;
                foreach (DataRow row in dt.Rows)
                {
                    DataRow r = dtExport.NewRow();
                    r["No."] = number;
                    r["Product No."] = row["ProductSN"].ToString();
                    r["Measurement"] = row["Measurement"].ToString();
                    r["Sort"] = row["Sort"].ToString();
                    r["Location"] = row["Location"].ToString();
                    r["Qty"] = row["Qty"].ToString();
                    r["Finished Weight(ct)"] = string.IsNullOrEmpty(row["FinishedWeight"].ToString()) ? "0" : row["FinishedWeight"].ToString();
                    r["Rough Weight(ct)"] = string.IsNullOrEmpty(row["RoughWeight"].ToString()) ? "0" : row["RoughWeight"].ToString();
                    r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
                    r["Shape"] = row["Shape"].ToString();
                    r["CertificateNo"] = row["CertificateNo"].ToString();
                    r["Color"] = row["Color"].ToString();
                    r["Clarity"] = row["Clarity"].ToString();
                    r["Polish"] = row["Polish"].ToString();
                    dtExport.Rows.Add(r);
                    number++;
                }
                gv.DataSource = dtExport;
                gv.DataBind();

                Export2(gv);
            }
        }

        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>
        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    GridViewExportUtil.PrepareControlForExport(current);
                }
            }
        }
    }

    public class AsposeCell
    {
        public static void Export(DataTable dt)
        {
            var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";


            MemoryStream ms = OutFileToStream(dt);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());

            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.End();


        }

        public static void Export(DataTable dt, string xlsName)
        {
            var name = xlsName + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";


            MemoryStream ms = OutFileToStream(dt);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());

            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.End();


        }

        public static void Export(MemoryStream ms)
        {
            var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";



            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());

            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.End();


        }

        public static void Export(MemoryStream ms, string name)
        {


            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            if (name.ToLower().Contains(".xlsm"))
            {
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
            }
            HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());

            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.End();


        }

        public static MemoryStream OutFileToStream(DataTable dt)
        {
            Workbook workbook = new Workbook(); //工作簿 

            workbook.Worksheets.Clear();

            for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
            {

                workbook.Worksheets.Add("" + j);
                Worksheet sheet = workbook.Worksheets[j];
                Cells cells = sheet.Cells;//单元格 

                //为标题设置样式     
                Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式 
                styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                styleTitle.Font.Name = "宋体";//文字字体 
                styleTitle.Font.Size = 18;//文字大小 
                styleTitle.Font.IsBold = true;//粗体 


                //样式2 
                Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式 
                style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                style2.Font.Name = "宋体";//文字字体 
                style2.Font.Size = 14;//文字大小 
                style2.Font.IsBold = true;//粗体 
                style2.IsTextWrapped = false;//单元格内容自动换行 

                //样式3 
                Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式 
                style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                style3.Font.Name = "宋体";//文字字体 
                style3.Font.Size = 12;//文字大小 
                style2.IsTextWrapped = false;//单元格内容自动换行 

                int Colnum = dt.Columns.Count;//表格列数 
                int Rownum = dt.Rows.Count;//表格行数 

                //生成行2 列名行 
                for (int i = 0; i < Colnum; i++)
                {

                    cells[0, i].PutValue(dt.Columns[i].ColumnName);
                    cells[0, i].SetStyle(style2);
                    cells.SetRowHeight(0, 25);
                    //for (int col = 0; col < Colnum; col++)
                    //{
                    //    sheet.AutoFitColumn(col, 0, Rownum-1);
                    //}
                    for (int col = 0; col < Colnum; col++)
                    {

                        cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
                    }

                }

                //生成数据行 
                for (int i = 0; i < 65534; i++)
                {
                    if ((j * 65534 + i) >= Rownum)
                    {
                        break;
                    }
                    for (int k = 0; k < Colnum; k++)
                    {

                        cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
                        cells[1 + i, k].SetStyle(style3);
                    }
                    cells.SetRowHeight(1 + i, 24);

                }
            }

            MemoryStream ms = workbook.SaveToStream();

            return ms;
        }

        public static MemoryStream OutFileToStream(DataSet ds, List<String> SheetNameList)
        {
            Workbook workbook = new Workbook(); //工作簿 

            workbook.Worksheets.Clear();
            int sheetIndex = 0;
            for (int jj = 0; jj < ds.Tables.Count; jj++)
            {
                DataTable dt = ds.Tables[jj];
                for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
                {

                    workbook.Worksheets.Add(sheetIndex + SheetNameList[jj]);
                    Worksheet sheet = workbook.Worksheets[sheetIndex];
                    sheetIndex++;
                    Cells cells = sheet.Cells;//单元格 

                    //为标题设置样式     
                    Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式 
                    styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                    styleTitle.Font.Name = "宋体";//文字字体 
                    styleTitle.Font.Size = 18;//文字大小 
                    styleTitle.Font.IsBold = true;//粗体 


                    //样式2 
                    Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式 
                    style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                    style2.Font.Name = "宋体";//文字字体 
                    style2.Font.Size = 14;//文字大小 
                    style2.Font.IsBold = true;//粗体 
                    style2.IsTextWrapped = false;//单元格内容自动换行 

                    //样式3 
                    Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式 
                    style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                    style3.Font.Name = "宋体";//文字字体 
                    style3.Font.Size = 12;//文字大小 
                    style2.IsTextWrapped = false;//单元格内容自动换行 

                    int Colnum = dt.Columns.Count;//表格列数 
                    int Rownum = dt.Rows.Count;//表格行数 

                    //生成行2 列名行 
                    for (int i = 0; i < Colnum; i++)
                    {

                        cells[0, i].PutValue(dt.Columns[i].ColumnName);
                        cells[0, i].SetStyle(style2);
                        cells.SetRowHeight(0, 25);
                        //for (int col = 0; col < Colnum; col++)
                        //{
                        //    sheet.AutoFitColumn(col, 0, Rownum-1);
                        //}
                        for (int col = 0; col < Colnum; col++)
                        {

                            cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
                        }

                    }

                    //生成数据行 
                    for (int i = 0; i < 65534; i++)
                    {
                        if ((j * 65534 + i) >= Rownum)
                        {
                            break;
                        }
                        for (int k = 0; k < Colnum; k++)
                        {

                            cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
                            cells[1 + i, k].SetStyle(style3);
                        }
                        cells.SetRowHeight(1 + i, 24);

                    }
                }

            }
            MemoryStream ms = workbook.SaveToStream();

            return ms;
        }
    }

    public class FileToExcel
    {
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            try
            {
                string fileExt = Path.GetExtension(file).ToLower();
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                    if (fileExt == ".xlsx")
                    { workbook = new XSSFWorkbook(fs); }
                    else if (fileExt == ".xls")
                    { workbook = new HSSFWorkbook(fs); }
                    else { workbook = null; }
                    if (workbook == null) { return null; }
                    ISheet sheet = workbook.GetSheetAt(0);

                    //表头  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    List<int> columns = new List<int>();
                    for (int i = 0; i < header.LastCellNum; i++)
                    {
                        ICell cell = header.GetCell(i);
                        var FillForegroundColor = cell.CellStyle.FillForegroundColor.ToString();
                        object obj = GetValueType(cell);
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            //dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        }
                        else
                        {
                            DataColumn dc = new DataColumn(obj.ToString());
                            if (FillForegroundColor == "15")
                                dc.AllowDBNull = false;
                            else
                                dc.AllowDBNull = true;
                            dt.Columns.Add(dc);
                            columns.Add(i);
                        }
                    }

                    //判断模板栏位是否正确 略
                    #region 判断模板是否正确



                    #endregion

                    //end 判断模板栏位正确

                    //数据  
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                    {
                        DataRow dr = dt.NewRow();
                        bool hasValue = false;
                        foreach (int j in columns)
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            if (!string.IsNullOrWhiteSpace(dr[j].ToString()))
                            {
                                hasValue = true;
                            }
                            else if (!dt.Columns[j].AllowDBNull)
                            {
                                string msg = "第 " + i + " 行,列" + dt.Columns[j].ColumnName + "没有输入值";
                                throw new Exception(msg);
                            }
                        }
                        if (hasValue)
                        {
                            dt.Rows.Add(dr);
                        }
                    }
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        public static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: 
                    //NUMERIC:  
                    //{
                    //   var time= cell.DateCellValue;
                    //    if (1==1)
                    //    return cell.NumericCellValue;
                    //}
                    if (HSSFDateUtil.IsCellDateFormatted(cell))
                    {
                       return cell.DateCellValue;
                    }
                    else
                    {
                       return cell.NumericCellValue;
                    }

                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
            return cell.StringCellValue;
        }
    }
}