using BLL;
using Model;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace FineUIPro.Web.CPT
{
    public partial class CPTReportList : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 绑定表格
                BindGrid();
                if (CurrUser.Account == Const.Gly)
                {
                    this.btnDelete.Hidden = false;
                }
                else
                {
                    this.btnDelete.Hidden = true;
                }
            }
        }
        #region 绑定数据
        /// 
        /// 绑定CPTlist
        /// 
        private void BindGrid(string CPT_No = "")
        {
            string strSql = @"SELECT cpt.ID,cpt.CPT_No,cpt.Contract_No,
                                    (cpt.ContractorEng+' '+cpt.ContractorCN) AS Contractor,
                                    cpt.FC_Desctription,cpt.Report_Date,ps.PriceScheme,
                                    cpt.FC_Start_Date,cpt.FC_End_Date,u.UserName
                              FROM dbo.CPTList cpt
                              LEFT JOIN dbo.Base_PriceScheme ps ON ps.PriceSchemeId=cpt.FC_Price_Scheme
							  LEFT JOIN dbo.Sys_User u ON u.UserId = cpt.UserId
                              WHERE 1=1";
            List listStr = new List();
            if (!string.IsNullOrEmpty(txtContract_No.Text))
            {
                strSql = strSql + " AND cpt.Contract_No=@Contract_No";
                listStr.Add(new SqlParameter("@Contract_No", txtContract_No.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(CPT_No))
            {
                strSql = strSql + " AND CHARINDEX(cpt.CPT_No,@CPT_No)>0";
                //strSql = strSql + " AND cpt.CPT_No=@CPT_No";
                listStr.Add(new SqlParameter("@CPT_No", CPT_No));
            }
            strSql = strSql + "  ORDER BY cpt.Report_Date DESC";
            SqlParameter[] parameter = listStr.ToArray();
            
            DataTable dt = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = dt.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, dt);
            Grid1.DataSource = table;
            Grid1.DataBind();
            //List sesCPTList = new List();
            //Expression> express = PredicateExtensions.True();
            //if (!string.IsNullOrEmpty(txtContract_No.Text))
            //{
            //    express = express.And(p => p.Contract_No == txtContract_No.Text.Trim());
            //}
            //if (!string.IsNullOrEmpty(CPT_No))
            //{
            //    express = express.And(p => p.CPT_No == CPT_No.Trim());
            //}
            //sesCPTList = Funs.DB.CPTList.Where(express).OrderByDescending(p => p.Report_Date).ToList();
            //Grid1.RecordCount = sesCPTList.Count;
            //var table = this.GetPagedDataTable(Grid1, sesCPTList);
            //Grid1.DataSource = table;
            //Grid1.DataBind();
        }
        /// 
        /// 绑定SESList
        /// 
        private void BindGrid1(string CPT_No)
        {
            if (!string.IsNullOrEmpty(CPT_No))
            {
                string strSql = @" SELECT * FROM dbo.SESList WHERE CPT_No=@CPT_No";
                List listStr = new List();
                listStr.Add(new SqlParameter("@CPT_No", CPT_No));
                SqlParameter[] parameter = listStr.ToArray();
                DataTable dt = SQLHelper.GetDataTableRunText(strSql, parameter);
                Grid2.RecordCount = dt.Rows.Count;
                //var table = this.GetPagedDataTable(Grid2, tb);
                Grid2.DataSource = dt;
                Grid2.DataBind();
                //List sesSESList = new List();
                //Expression> express = PredicateExtensions.True();
                //express = express.And(p => p.CPT_No == CPT_No);
                //if (!string.IsNullOrEmpty(SES_No))
                //{
                //    express = express.And(p => p.SES == SES_No.Trim());
                //}
                //sesSESList = Funs.DB.SESList.Where(express).OrderByDescending(p => p.Submit_Date).ToList();
                //Grid2.DataSource = sesSESList;
                //Grid2.DataBind();
            }
            else
            {
                Grid2.DataSource = null;
                Grid2.DataBind();
            }
        }
        #endregion
        #region 打印
        /// 
        /// 打印
        /// 
        /// 
        /// 
        //protected void btnView_Click(object sender, EventArgs e)
        //{
        //    if (Grid1.SelectedRowIndexArray.Length == 0)
        //    {
        //        Alert.ShowInParent("Please select at least one record!");
        //        return;
        //    }
        //    string No = Grid1.SelectedRowID;
        //    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../Report/ReportPrint.aspx?report=3&CptNo=" + No + "", "Print - ")));
        //}
        /// 
        /// 右键编辑事件
        /// 
        /// 
        /// 
        //protected void btnMenuEdit_Click(object sender, EventArgs e)
        //{
        //    btnView_Click(null, null);
        //}
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        //protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        //{
        //    btnView_Click(null, null);
        //}
        #endregion
        #region 关闭弹出窗口
        /// 
        /// 关闭窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 分页、排序
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        /// 
        /// 分页显示条数下拉框
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion
        #region 选择加载
        /// 
        /// 选择加载
        /// 
        /// 
        /// 
        protected void Grid1_RowClick(object sender, GridRowClickEventArgs e)
        {
            BindGrid1(this.Grid1.SelectedRowID);
        }
        #endregion
        #region 打印
        /// 
        /// 打印
        /// 
        /// 
        /// 
        //protected void btnPrint_Click(object sender, EventArgs e)
        //{
        //    if (Grid1.SelectedRowIndexArray.Length == 0)
        //    {
        //        Alert.ShowInParent("Please select at least one record!");
        //        return;
        //    }
        //    string No = Grid1.SelectedRowID;
        //    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../Report/ReportPrint.aspx?report=3&CptNo=" + No + "", "Print - ")));
        //}
        #endregion
        #region 删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Grid1.SelectedRowID))
            {
                var cptList = from x in Funs.DB.CPTList where x.CPT_No == Grid1.SelectedRowID select x;
                var sesList = from x in Funs.DB.SESList where x.CPT_No == Grid1.SelectedRowID select x;
                var sesNoList = sesList.Select(p => p.SES).ToList();
                var deleteReportCpt = from x in Funs.DB.FC_SESReportToCPT where sesNoList.Contains(x.SES_No) select x;
                Funs.DB.FC_SESReportToCPT.DeleteAllOnSubmit(deleteReportCpt);
                Funs.DB.SESList.DeleteAllOnSubmit(sesList);
                Funs.DB.CPTList.DeleteAllOnSubmit(cptList);
                Funs.DB.SubmitChanges();
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete CPT");
                // 重新绑定表格
                BindGrid();
                BindGrid1("");
                ShowNotify("Delete successfully!", MessageBoxIcon.Success);
            }
            else
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
        }
        #endregion
        #region 搜索
        /// 
        /// 搜索
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSES_No.Text.Trim()))
            {
                List sesModel = null;
                if (txtSES_No.Text.Trim().Contains(",") || txtSES_No.Text.Trim().Contains(","))
                {
                    if (txtSES_No.Text.Trim().Contains(","))
                    {
                        string[] sesList = txtSES_No.Text.Trim().Split(',').ToArray();
                        sesModel = Funs.DB.SESList.Where(p => sesList.Contains(p.SES)).ToList();
                    }
                    else
                    {
                        string[] sesList = txtSES_No.Text.Trim().Split(',').ToArray();
                        sesModel = Funs.DB.SESList.Where(p => sesList.Contains(p.SES)).ToList();
                    }
                }
                else
                {
                    sesModel = Funs.DB.SESList.Where(p => p.SES == txtSES_No.Text.Trim()).ToList();
                }
                //var sesModel = Funs.DB.SESList.Where(p => sesList.Contains(p.SES));
                if (sesModel != null)
                {
                    if (sesModel.Count() == 1)
                    {
                        BindGrid(sesModel.First().CPT_No.Trim());
                        BindGrid1(sesModel.First().CPT_No.Trim());
                        var sesCPTModel = Funs.DB.CPTList.Where(p => p.CPT_No == sesModel.First().CPT_No.Trim()).OrderByDescending(p => p.Report_Date).FirstOrDefault();
                        var UserSESRelatedData = Funs.DB.View_FC_SESRelatedData.FirstOrDefault(p => p.FO_NO == sesCPTModel.Contract_No);
                        Alert.ShowInTop("CPT No:" + sesModel.First().CPT_No + ";Contract No. (" + sesCPTModel.Contract_No + ");Contract Admin (" + UserSESRelatedData.Contract_Admin + ")", MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        string[] cpt = sesModel.Select(p => p.CPT_No).ToArray();
                        string cptList = string.Join(",", cpt);
                        BindGrid(cptList);
                        BindGrid1("");
                    }
                }
                else
                {
                    Alert.ShowInTop("No CPT;No Contract No.;No Contract Admin", MessageBoxIcon.Information);
                    return;
                }
            }
            else
            {
                BindGrid();
            }
        }
        #endregion
        #region 格式化字符串
        /// 
        /// 承包商
        /// 
        /// 
        /// 
        protected string ConvertContract(object con)
        {
            if (con != null)
            {
                var contractor = BLL.ContractorService.GetContractorById(con.ToString());
                if (contractor != null)
                {
                    return contractor.Contractor + contractor.ContractorCN;
                }
            }
            return null;
        }
        protected string ConvertPriceScheme(object ps)
        {
            if (ps != null)
            {
                var priceScheme = BLL.PriceSchemeService.GetPriceSchemeById(ps.ToString());
                if (priceScheme != null)
                {
                    return priceScheme.PriceScheme;
                }
            }
            return null;
        }
        #endregion
        #region 导出
        /// 
        /// 导出
        /// 
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
            string cptNo = Grid1.SelectedRowID;
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //模板文件
            string TempletFileName = rootPath + "CPTReport.xlsx";
            //导出文件
            string filePath = rootPath + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string ReportFileName = filePath + "out.xls";
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
            XSSFSheet ws = (XSSFSheet)hssfworkbook.GetSheetAt(0);
            var cptModel = Funs.DB.CPTList.FirstOrDefault(p => p.CPT_No == cptNo);
            if (cptModel != null)
            {
                //CTE/D_Manager经理
                var CTED_List = from a in Funs.DB.Sys_User
                                join b in Funs.DB.Sys_Role
                                on a.RoleId equals b.RoleId
                                where a.IsPost == true && b.RoleName.Contains("CTE/D Manager")
                                select new { a.UserName, a.ChineseName };
                var CT_Director = from x in Funs.DB.Sys_User
                                  join y in Funs.DB.Sys_Role on x.RoleId equals y.RoleId
                                  where x.UserId == cptModel.CT_Director
                                  select new { x.UserName, x.ChineseName };
                var CT_GM = from x in Funs.DB.Sys_User
                            join y in Funs.DB.Sys_Role on x.RoleId equals y.RoleId
                            where x.IsPost == true && y.RoleName.Contains("CT GM")
                            select new { x.UserName, x.ChineseName };
                var basePriceScheme = Funs.DB.Base_PriceScheme.FirstOrDefault(p => p.PriceSchemeId == cptModel.FC_Price_Scheme);
                var cptMainModel = Funs.DB.FC_SESReportToCPT.Where(p => p.FO == cptModel.Contract_No).ToList();
                var sesData = Funs.DB.FC_SESRelatedData.FirstOrDefault(p => p.FO_NO == cptModel.Contract_No);
                var UserSESRelatedData = Funs.DB.View_FC_SESRelatedData.FirstOrDefault(p => p.FO_NO == cptModel.Contract_No);
                var conUser = BLL.Sys_UserService.GetUsersByUserId(cptModel.UserId);
                #region 左边
                //创建时间
                if (ws.GetRow(0).GetCell(1) == null) ws.GetRow(1).CreateCell(0);
                ws.GetRow(1).GetCell(0).SetCellValue(string.Format("{0:yyyy/MM/dd HH:mm:ss}", cptModel.Report_Date));
                //CPT_No
                if (ws.GetRow(0).GetCell(14) == null) ws.GetRow(0).CreateCell(14);
                ws.GetRow(0).GetCell(14).SetCellValue("CPT No.  " + cptModel.CPT_No);
                //Contract No.合同号
                if (ws.GetRow(6).GetCell(3) == null) ws.GetRow(6).CreateCell(3);
                ws.GetRow(6).GetCell(3).SetCellValue(cptModel.Contract_No);
                //Contractor 承包商
                if (ws.GetRow(10).GetCell(3) == null) ws.GetRow(10).CreateCell(3);
                ws.GetRow(10).GetCell(3).SetCellValue(cptModel.ContractorEng + "\n" + cptModel.ContractorCN);
                //FC Description 框架合同描
                if (ws.GetRow(14).GetCell(3) == null) ws.GetRow(14).CreateCell(3);
                ws.GetRow(14).GetCell(3).SetCellValue(UserSESRelatedData.Discipline_Eng + "\n" + UserSESRelatedData.Discipline_CN);
                //FC Price scheme 承包商价格方案
                if (ws.GetRow(18).GetCell(3) == null) ws.GetRow(18).CreateCell(3);
                ws.GetRow(18).GetCell(3).SetCellValue(UserSESRelatedData.Pricing_Scheme);
                //FC Valid period 框架合同有效期开始日期
                if (ws.GetRow(22).GetCell(3) == null) ws.GetRow(22).CreateCell(3);
                ws.GetRow(22).GetCell(3).SetCellValue(UserSESRelatedData.Validate_Date.HasValue ? string.Format("{0:yyyy-MM-dd}", UserSESRelatedData.Validate_Date) : "");
                //结束日期
                if (ws.GetRow(22).GetCell(7) == null) ws.GetRow(22).CreateCell(7);
                ws.GetRow(22).GetCell(7).SetCellValue(UserSESRelatedData.Expire_Date.HasValue ? string.Format("{0:yyyy-MM-dd}", UserSESRelatedData.Expire_Date) : "");
                //Amount to be paid (Net) 应付净额
                if (ws.GetRow(34).GetCell(0) == null) ws.GetRow(34).CreateCell(0);
                ws.GetRow(34).GetCell(0).SetCellValue(cptModel.Net_Amount != null ? string.Format("{0:N}", cptModel.Net_Amount.Value) : "0");//cptModel.Net_Amount.Value.ToString("0.##") : "0");
                //Amount to be paid (Including tax)应付含税额
                if (ws.GetRow(34).GetCell(3) == null) ws.GetRow(34).CreateCell(3);
                decimal? taxAmount = Funs.GetNewDecimal(cptModel.Tax_Amount);
                ws.GetRow(34).GetCell(3).SetCellValue(taxAmount != null ? string.Format("{0:N}", taxAmount) : "0");//(cptModel.Tax_Amount);
                //Tax税率
                if (ws.GetRow(34).GetCell(7) == null) ws.GetRow(34).CreateCell(7);
                ws.GetRow(34).GetCell(7).SetCellValue(cptModel.Tax != null ? (cptModel.Tax.Value * 100).ToString("0.##") + "%" : "0");
                //Currency币种
                if (ws.GetRow(34).GetCell(8) == null) ws.GetRow(34).CreateCell(8);
                ws.GetRow(34).GetCell(8).SetCellValue(cptModel.Currency);
                //Last Payment of This Contract本合同最后一笔付款Y/N
                if (ws.GetRow(38).GetCell(7) == null) ws.GetRow(38).CreateCell(7);
                ws.GetRow(38).GetCell(7).SetCellValue(cptModel.Last_Payment);
                #endregion
                #region 右边
                //Contract Administrator合同员
                if (ws.GetRow(10).GetCell(12) == null) ws.GetRow(10).CreateCell(12);
                ws.GetRow(10).GetCell(12).SetCellValue(conUser != null ? conUser.UserName + "\n" + conUser.ChineseName : "");
                //ws.GetRow(10).GetCell(12).SetCellValue(UserSESRelatedData != null ? UserSESRelatedData.Contract_Admin + "\n" + UserSESRelatedData.ChineseName : "");
                //CTE/D Manager CTE/D 经理
                if (ws.GetRow(14).GetCell(12) == null) ws.GetRow(14).CreateCell(12);
                ws.GetRow(14).GetCell(12).SetCellValue(CTED_List != null && CTED_List.Count() > 0 ? CTED_List.FirstOrDefault().UserName + "\n" + CTED_List.FirstOrDefault().ChineseName : "");
                //时间进程,费用进程
                if (sesData != null)
                {
                    bool timebool = true;
                    float timeProgress = 0f;
                    #region 时间进程
                    if ((sesData.Validate_Date != null && sesData.Expire_Date != null))
                    {
                        //开始日期大于结束日期(肯定为数据错误,默认为0)
                        if (sesData.Validate_Date < sesData.Expire_Date)
                        {
                            //开始日期大于当前日期,为0
                            if (sesData.Validate_Date > DateTime.Now)
                            {
                                timebool = false;
                                timeProgress = 0;
                            }
                            //结束日期小于当前日期
                            if (sesData.Expire_Date < DateTime.Now)
                            {
                                timebool = false;
                                timeProgress = 1;
                            }
                            if (timebool)
                            {
                                float nowSpan = GetTimeSpan(sesData.Validate_Date.Value, DateTime.Now);
                                float allSpan = GetTimeSpan(sesData.Validate_Date.Value, sesData.Expire_Date.Value);
                                timeProgress = nowSpan / allSpan;
                            }
                            //Time Progress 时间进程
                            if (ws.GetRow(19).GetCell(12) == null) ws.GetRow(19).CreateCell(12);
                            ws.GetRow(19).GetCell(12).SetCellValue(timeProgress);
                        }
                    }
                    #endregion
                    #region 费用进程
                    float coseProgress = 0f;
                    decimal? actualNet = BLL.CPTListService.getSumNetValueByFo(cptModel.Contract_No);
                    if (sesData.Actual_Budget != null && actualNet != null)
                    {
                        float actual = (float)actualNet;
                        float total = (float)sesData.Actual_Budget;
                        coseProgress = actual / total;
                        //Cost Progres 费用进程
                        if (ws.GetRow(12).GetCell(13) == null) ws.GetRow(23).CreateCell(12);
                        ws.GetRow(23).GetCell(12).SetCellValue(coseProgress);
                    }
                    #endregion
                }
                //CT Director CT总监 打印体姓名
                if (ws.GetRow(34).GetCell(12) == null) ws.GetRow(34).CreateCell(12);
                ws.GetRow(34).GetCell(12).SetCellValue(CT_Director != null && CT_Director.Count() > 0 ? CT_Director.FirstOrDefault().UserName + "\n" + CT_Director.FirstOrDefault().ChineseName : "");
                //CT GM CT总经理 打印体姓名
                if (ws.GetRow(38).GetCell(12) == null) ws.GetRow(38).CreateCell(12);
                ws.GetRow(38).GetCell(12).SetCellValue(CT_GM != null && CT_GM.Count() > 0 ? CT_GM.FirstOrDefault().UserName + "\n" + CT_GM.FirstOrDefault().ChineseName : "N/A");
                //CT Director CT总监 签字 CT GM CT总经理 签字
                if (taxAmount != null && taxAmount <= 300000)
                {
                    if (ws.GetRow(34).GetCell(14) == null) ws.GetRow(38).CreateCell(14);
                    ws.GetRow(34).GetCell(14).SetCellValue("N/A");
                    if (ws.GetRow(38).GetCell(14) == null) ws.GetRow(38).CreateCell(14);
                    ws.GetRow(38).GetCell(14).SetCellValue("N/A");
                }
                else if (taxAmount != null && taxAmount <= 500000)
                {
                    if (ws.GetRow(38).GetCell(14) == null) ws.GetRow(38).CreateCell(14);
                    ws.GetRow(38).GetCell(14).SetCellValue("N/A");
                }
                #endregion
                #region Remark 备注
                if (ws.GetRow(43).GetCell(0) == null) ws.GetRow(43).CreateCell(0);
                ws.GetRow(43).GetCell(0).SetCellValue("Remark 备注:" + " \n\n\n\n\n\n\n\n\n\n ");
                if (cptMainModel.Count > 0)
                {
                    if (cptMainModel.Count(p => !string.IsNullOrEmpty(p.WBS) || !string.IsNullOrEmpty(p.Network)) > 0)
                    {
                        //var webOrNetWork = from x in cptMainModel
                        //                   join y in Funs.DB.FC_SESRelatedData on x.FO equals y.FO_NO
                        //                   where (!string.IsNullOrEmpty(x.WBS) || !string.IsNullOrEmpty(x.Network))
                        //                         && y.ConstRecords == "Y"
                        //                   select x;
                        var webOrNetWork = from x in Funs.DB.SESList
                                           join y in Funs.DB.FC_SESReportToCPT on x.SES equals y.SES_No
                                           join z in Funs.DB.FC_SESRelatedData on y.FO equals z.FO_NO
                                           where x.CPT_No == cptNo && z.ConstRecords == "Y"
                                                && ((y.WBS != null && y.WBS != "") || (y.Network != null && y.Network != ""))
                                           select x;
                        if (webOrNetWork.Count() > 0)
                        {
                            var q = from x in webOrNetWork select x.SES;
                            //var webOrNetWork = cptMainModel.Where(p => !string.IsNullOrEmpty(p.WBS) || !string.IsNullOrEmpty(p.Network)).Select(p => p.SES_No).ToList();
                            ws.GetRow(43).GetCell(0).SetCellValue("Remark 备注:Construction records possibly needed /可能需要交工资料的:\n" + string.Join("/", q) + " \n\n\n\n\n\n\n\n Please refer to the “Confirmation of Construction Records Submission” enclosed for the status of submission.交工资料提交情况请见后附的“交工资料提交确认”。");
                        }
                    }
                }
                #endregion
                #region 表格
                if (ws.GetRow(61).GetCell(14) == null) ws.GetRow(61).CreateCell(14);
                ws.GetRow(61).GetCell(14).SetCellValue("CPT No. " + cptModel.CPT_No);
                var sesSESList = Funs.DB.SESList.Where(p => p.CPT_No == cptNo).ToList();
                int i = 1;
                int rowindex = 65;
                //全局边框靠右
                ICellStyle style = hssfworkbook.CreateCellStyle();
                style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.Alignment = HorizontalAlignment.Right;
                //全局边框靠左
                ICellStyle style1 = hssfworkbook.CreateCellStyle();
                style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.Alignment = HorizontalAlignment.Left;
                //全局边框靠右千分位
                IDataFormat dataformat = hssfworkbook.CreateDataFormat();
                ICellStyle styleQfw = hssfworkbook.CreateCellStyle();
                styleQfw.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                styleQfw.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                styleQfw.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                styleQfw.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                styleQfw.VerticalAlignment = VerticalAlignment.Center;
                styleQfw.Alignment = HorizontalAlignment.Right;
                styleQfw.DataFormat = dataformat.GetFormat("#,##0.00");
                #region 头部
                //列头边框
                ICellStyle titleStyle = hssfworkbook.CreateCellStyle();
                titleStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle.Alignment = HorizontalAlignment.Left;
                //字体
                IFont font = hssfworkbook.CreateFont();
                font.FontHeightInPoints = 10;
                font.IsBold = false;
                font.FontName = "Arial";
                titleStyle.SetFont(font);
                //背景色
                titleStyle.FillPattern = FillPattern.SolidForeground;
                titleStyle.FillForegroundColor = HSSFColor.LightYellow.Index;
                //列头边框1
                ICellStyle titleStyle1 = hssfworkbook.CreateCellStyle();
                titleStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle1.Alignment = HorizontalAlignment.Left;
                //字体
                IFont font1 = hssfworkbook.CreateFont();
                font1.FontHeightInPoints = 10;
                font1.IsBold = true;
                font1.FontName = "Arial";
                titleStyle1.SetFont(font1);
                //列头边框2
                ICellStyle titleStyle2 = hssfworkbook.CreateCellStyle();
                titleStyle2.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle2.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle2.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle2.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                titleStyle2.Alignment = HorizontalAlignment.Left;
                //字体
                IFont font2 = hssfworkbook.CreateFont();
                font2.FontHeightInPoints = 10;
                font2.IsBold = false;
                font2.FontName = "Arial";
                titleStyle2.SetFont(font2);
                //背景色
                titleStyle2.FillPattern = FillPattern.SolidForeground;
                titleStyle2.FillForegroundColor = HSSFColor.Grey50Percent.Index;
                #endregion
                foreach (var itemSes in sesSESList)
                {
                    ws.CreateRow(rowindex);
                    ws.GetRow(rowindex).HeightInPoints = 19.8f;
                    //添加表头
                    if (i % 33 == 0)
                    {
                        if (ws.GetRow(rowindex) == null) ws.CreateRow(rowindex);
                        if (ws.GetRow(rowindex + 1) == null) ws.CreateRow(rowindex + 1);
                        ws.GetRow(rowindex + 1).HeightInPoints = 19.8f;
                        if (ws.GetRow(rowindex + 2) == null) ws.CreateRow(rowindex + 2);
                        ws.GetRow(rowindex + 2).HeightInPoints = 19.8f;
                        if (ws.GetRow(rowindex + 3) == null) ws.CreateRow(rowindex + 3);
                        ws.GetRow(rowindex + 3).HeightInPoints = 19.8f;
                        if (ws.GetRow(rowindex + 4) == null) ws.CreateRow(rowindex + 4);
                        ws.GetRow(rowindex + 4).HeightInPoints = 19.8f;
                        if (i == 33)
                        {
                            if (ws.GetRow(rowindex + 5) == null) ws.CreateRow(rowindex + 5);
                            ws.GetRow(rowindex + 5).HeightInPoints = 19.8f;
                            rowindex = rowindex + 6;
                        }
                        else
                        {
                            rowindex = rowindex + 5;
                        }
                        #region cpt标题
                        //字体
                        ICellStyle cptStyle1 = hssfworkbook.CreateCellStyle();
                        cptStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.None;
                        cptStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.None;
                        cptStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.None;
                        cptStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.None;
                        cptStyle1.VerticalAlignment = VerticalAlignment.Center;
                        cptStyle1.Alignment = HorizontalAlignment.Right;
                        //字体
                        IFont cptfont = hssfworkbook.CreateFont();
                        cptfont.FontHeightInPoints = 14;
                        cptfont.IsBold = false;
                        cptfont.FontName = "Arial";
                        cptStyle1.SetFont(cptfont);
                        //创建
                        ws.CreateRow(rowindex - 1);
                        ws.CreateRow(rowindex - 2);
                        ws.GetRow(rowindex - 1).HeightInPoints = ws.GetRow(rowindex - 2).HeightInPoints = 19.8f;
                        //赋值
                        var regiont = new CellRangeAddress(rowindex - 2, rowindex - 1, 14, 18);
                        ws.AddMergedRegion(regiont);
                        if (ws.GetRow(rowindex - 2).GetCell(14) == null) ws.GetRow(rowindex - 2).CreateCell(14);
                        ws.GetRow(rowindex - 2).GetCell(14).SetCellValue("CPT No. " + cptModel.CPT_No);
                        ws.GetRow(rowindex - 2).GetCell(14).CellStyle = cptStyle1;
                        #endregion
                        #region 头1
                        //列1
                        if (ws.GetRow(rowindex) == null) ws.CreateRow(rowindex);
                        if (ws.GetRow(rowindex).GetCell(0) == null) ws.GetRow(rowindex).CreateCell(0);
                        ws.GetRow(rowindex).GetCell(0).SetCellValue("");
                        ws.GetRow(rowindex).GetCell(0).CellStyle = titleStyle;
                        //列2
                        if (ws.GetRow(rowindex).GetCell(1) == null) ws.GetRow(rowindex).CreateCell(1);
                        if (ws.GetRow(rowindex).GetCell(2) == null) ws.GetRow(rowindex).CreateCell(2);
                        if (ws.GetRow(rowindex).GetCell(3) == null) ws.GetRow(rowindex).CreateCell(3);
                        if (ws.GetRow(rowindex).GetCell(4) == null) ws.GetRow(rowindex).CreateCell(4);
                        if (ws.GetRow(rowindex).GetCell(5) == null) ws.GetRow(rowindex).CreateCell(5);
                        if (ws.GetRow(rowindex).GetCell(6) == null) ws.GetRow(rowindex).CreateCell(6);
                        if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                        regiont = new CellRangeAddress(rowindex, rowindex, 1, 7);
                        ws.AddMergedRegion(regiont);
                        ws.GetRow(rowindex).GetCell(1).SetCellValue("Basic information");
                        ws.GetRow(rowindex).GetCell(1).CellStyle = ws.GetRow(rowindex).GetCell(2).CellStyle = ws.GetRow(rowindex).GetCell(3).CellStyle = ws.GetRow(rowindex).GetCell(4).CellStyle = ws.GetRow(rowindex).GetCell(5).CellStyle = ws.GetRow(rowindex).GetCell(6).CellStyle = ws.GetRow(rowindex).GetCell(7).CellStyle = titleStyle;
                        //列3
                        //if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                        //if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                        //regiont = new CellRangeAddress(rowindex, rowindex, 7, 8);
                        //ws.AddMergedRegion(regiont);
                        //ws.GetRow(rowindex).GetCell(7).SetCellValue("Work plan");
                        //ws.GetRow(rowindex).GetCell(7).CellStyle = ws.GetRow(rowindex).GetCell(8).CellStyle = titleStyle;
                        //列3
                        if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                        if (ws.GetRow(rowindex).GetCell(9) == null) ws.GetRow(rowindex).CreateCell(9);
                        if (ws.GetRow(rowindex).GetCell(10) == null) ws.GetRow(rowindex).CreateCell(10);
                        if (ws.GetRow(rowindex).GetCell(11) == null) ws.GetRow(rowindex).CreateCell(11);
                        if (ws.GetRow(rowindex).GetCell(12) == null) ws.GetRow(rowindex).CreateCell(12);
                        regiont = new CellRangeAddress(rowindex, rowindex, 8, 12);
                        ws.AddMergedRegion(regiont);
                        ws.GetRow(rowindex).GetCell(8).SetCellValue("Value info");
                        ws.GetRow(rowindex).GetCell(8).CellStyle = ws.GetRow(rowindex).GetCell(9).CellStyle = ws.GetRow(rowindex).GetCell(10).CellStyle = ws.GetRow(rowindex).GetCell(11).CellStyle = ws.GetRow(rowindex).GetCell(12).CellStyle = titleStyle2;
                        //列4
                        if (ws.GetRow(rowindex).GetCell(13) == null) ws.GetRow(rowindex).CreateCell(13);
                        if (ws.GetRow(rowindex).GetCell(14) == null) ws.GetRow(rowindex).CreateCell(14);
                        regiont = new CellRangeAddress(rowindex, rowindex, 13, 14);
                        ws.AddMergedRegion(regiont);
                        ws.GetRow(rowindex).GetCell(13).SetCellValue("Budget management");
                        ws.GetRow(rowindex).GetCell(13).CellStyle = ws.GetRow(rowindex).GetCell(14).CellStyle = titleStyle;
                        //列5
                        if (ws.GetRow(rowindex).GetCell(15) == null) ws.GetRow(rowindex).CreateCell(15);
                        ws.GetRow(rowindex).GetCell(15).SetCellValue("Deduction");
                        ws.GetRow(rowindex).GetCell(15).CellStyle = titleStyle2;
                        //列6
                        if (ws.GetRow(rowindex).GetCell(16) == null) ws.GetRow(rowindex).CreateCell(16);
                        if (ws.GetRow(rowindex).GetCell(17) == null) ws.GetRow(rowindex).CreateCell(17);
                        if (ws.GetRow(rowindex).GetCell(18) == null) ws.GetRow(rowindex).CreateCell(18);
                        regiont = new CellRangeAddress(rowindex, rowindex, 16, 18);
                        ws.AddMergedRegion(regiont);
                        ws.GetRow(rowindex).GetCell(16).SetCellValue("Duration(Days)");
                        ws.GetRow(rowindex).GetCell(16).CellStyle = ws.GetRow(rowindex).GetCell(17).CellStyle = ws.GetRow(rowindex).GetCell(18).CellStyle = titleStyle;
                        #endregion
                        #region 头2
                        if (ws.GetRow(rowindex + 1) == null) ws.CreateRow(rowindex + 1);
                        ws.GetRow(rowindex + 1).HeightInPoints = 19.8f;
                        //No.
                        if (ws.GetRow(rowindex + 1).GetCell(0) == null) ws.GetRow(rowindex + 1).CreateCell(0);
                        ws.GetRow(rowindex + 1).GetCell(0).SetCellValue("No.");
                        ws.GetRow(rowindex + 1).GetCell(0).CellStyle = titleStyle1;
                        //SES No.
                        if (ws.GetRow(rowindex + 1).GetCell(1) == null) ws.GetRow(rowindex + 1).CreateCell(1);
                        ws.GetRow(rowindex + 1).GetCell(1).SetCellValue("SES No.");
                        ws.GetRow(rowindex + 1).GetCell(1).CellStyle = titleStyle1;
                        //Short Description
                        regiont = new CellRangeAddress(rowindex + 1, rowindex + 1, 2, 7);
                        ws.AddMergedRegion(regiont);
                        if (ws.GetRow(rowindex + 1).GetCell(2) == null) ws.GetRow(rowindex + 1).CreateCell(2);
                        ws.GetRow(rowindex + 1).GetCell(2).SetCellValue("Short Description");
                        if (ws.GetRow(rowindex + 1).GetCell(3) == null) ws.GetRow(rowindex + 1).CreateCell(3);
                        if (ws.GetRow(rowindex + 1).GetCell(4) == null) ws.GetRow(rowindex + 1).CreateCell(4);
                        if (ws.GetRow(rowindex + 1).GetCell(5) == null) ws.GetRow(rowindex + 1).CreateCell(5);
                        if (ws.GetRow(rowindex + 1).GetCell(6) == null) ws.GetRow(rowindex + 1).CreateCell(6);
                        if (ws.GetRow(rowindex + 1).GetCell(7) == null) ws.GetRow(rowindex + 1).CreateCell(7);
                        ws.GetRow(rowindex + 1).GetCell(2).CellStyle = ws.GetRow(rowindex + 1).GetCell(3).CellStyle = ws.GetRow(rowindex + 1).GetCell(4).CellStyle = ws.GetRow(rowindex + 1).GetCell(5).CellStyle = ws.GetRow(rowindex + 1).GetCell(6).CellStyle = ws.GetRow(rowindex + 1).GetCell(7).CellStyle = titleStyle1;
                        //Start
                        //if (ws.GetRow(rowindex + 1).GetCell(7) == null) ws.GetRow(rowindex + 1).CreateCell(7);
                        //ws.GetRow(rowindex + 1).GetCell(7).SetCellValue("Start");
                        //ws.GetRow(rowindex + 1).GetCell(7).CellStyle = titleStyle1;
                        //End
                        //if (ws.GetRow(rowindex + 1).GetCell(8) == null) ws.GetRow(rowindex + 1).CreateCell(8);
                        //ws.GetRow(rowindex + 1).GetCell(8).SetCellValue("End");
                        //ws.GetRow(rowindex + 1).GetCell(8).CellStyle = titleStyle1;
                        //Budget(B)
                        if (ws.GetRow(rowindex + 1).GetCell(8) == null) ws.GetRow(rowindex + 1).CreateCell(8);
                        ws.GetRow(rowindex + 1).GetCell(8).SetCellValue("Budget(B)");
                        ws.GetRow(rowindex + 1).GetCell(8).CellStyle = titleStyle1;
                        //Quotation(Q)
                        if (ws.GetRow(rowindex + 1).GetCell(9) == null) ws.GetRow(rowindex + 1).CreateCell(9);
                        ws.GetRow(rowindex + 1).GetCell(9).SetCellValue("Quotation(Q)");
                        ws.GetRow(rowindex + 1).GetCell(9).CellStyle = titleStyle1;
                        //Net value(N)
                        if (ws.GetRow(rowindex + 1).GetCell(10) == null) ws.GetRow(rowindex + 1).CreateCell(10);
                        ws.GetRow(rowindex + 1).GetCell(10).SetCellValue("Net value(N)");
                        ws.GetRow(rowindex + 1).GetCell(10).CellStyle = titleStyle1;
                        //Incl. Tax(V)
                        if (ws.GetRow(rowindex + 1).GetCell(11) == null) ws.GetRow(rowindex + 1).CreateCell(11);
                        ws.GetRow(rowindex + 1).GetCell(11).SetCellValue("Incl. Tax(V)");
                        ws.GetRow(rowindex + 1).GetCell(11).CellStyle = titleStyle1;
                        //Punishment(P)
                        if (ws.GetRow(rowindex + 1).GetCell(12) == null) ws.GetRow(rowindex + 1).CreateCell(12);
                        ws.GetRow(rowindex + 1).GetCell(12).SetCellValue("Punishment(P)");
                        ws.GetRow(rowindex + 1).GetCell(12).CellStyle = titleStyle1;
                        //Deviation(N-B)改为:Deviation(N+P/(1+Tax))-B
                        if (ws.GetRow(rowindex + 1).GetCell(13) == null) ws.GetRow(rowindex + 1).CreateCell(13);
                        ws.GetRow(rowindex + 1).GetCell(13).SetCellValue("Deviation");
                        ws.GetRow(rowindex + 1).GetCell(13).CellStyle = titleStyle1;
                        //By perc.(N-B)/B改为:By perc.(N+P/(1+Tax)-B)/B
                        if (ws.GetRow(rowindex + 1).GetCell(14) == null) ws.GetRow(rowindex + 1).CreateCell(14);
                        ws.GetRow(rowindex + 1).GetCell(14).SetCellValue("By perc.");
                        ws.GetRow(rowindex + 1).GetCell(14).CellStyle = titleStyle1;
                        //Deduction(Q-V)
                        if (ws.GetRow(rowindex + 1).GetCell(15) == null) ws.GetRow(rowindex + 1).CreateCell(15);
                        ws.GetRow(rowindex + 1).GetCell(15).SetCellValue("Deduction(Q-(V+P))");
                        ws.GetRow(rowindex + 1).GetCell(15).CellStyle = titleStyle1;
                        //Con
                        if (ws.GetRow(rowindex + 1).GetCell(16) == null) ws.GetRow(rowindex + 1).CreateCell(16);
                        ws.GetRow(rowindex + 1).GetCell(16).SetCellValue("Con");
                        ws.GetRow(rowindex + 1).GetCell(16).CellStyle = titleStyle1;
                        //BoQ
                        if (ws.GetRow(rowindex + 1).GetCell(17) == null) ws.GetRow(rowindex + 1).CreateCell(17);
                        ws.GetRow(rowindex + 1).GetCell(17).SetCellValue("BoQ");
                        ws.GetRow(rowindex + 1).GetCell(17).CellStyle = titleStyle1;
                        //SES
                        if (ws.GetRow(rowindex + 1).GetCell(18) == null) ws.GetRow(rowindex + 1).CreateCell(18);
                        ws.GetRow(rowindex + 1).GetCell(18).SetCellValue("SES");
                        ws.GetRow(rowindex + 1).GetCell(18).CellStyle = titleStyle1;
                        #endregion
                        rowindex = rowindex + 2;
                    }
                    if (ws.GetRow(rowindex) == null) ws.CreateRow(rowindex);
                    ws.GetRow(rowindex).HeightInPoints = 19.8f;
                    //No.
                    if (ws.GetRow(rowindex).GetCell(0) == null) ws.GetRow(rowindex).CreateCell(0);
                    ws.GetRow(rowindex).GetCell(0).SetCellValue(i);
                    ws.GetRow(rowindex).GetCell(0).CellStyle = style;
                    //SES No.
                    if (ws.GetRow(rowindex).GetCell(1) == null) ws.GetRow(rowindex).CreateCell(1);
                    ws.GetRow(rowindex).GetCell(1).SetCellValue(itemSes.SES);
                    ws.GetRow(rowindex).GetCell(1).CellStyle = style;
                    //Short Description
                    CellRangeAddress regiond = new CellRangeAddress(rowindex, rowindex, 2, 7);
                    ws.AddMergedRegion(regiond);
                    if (ws.GetRow(rowindex).GetCell(2) == null) ws.GetRow(rowindex).CreateCell(2);
                    ws.GetRow(rowindex).GetCell(2).SetCellValue(itemSes.Short_Description);
                    if (ws.GetRow(rowindex).GetCell(3) == null) ws.GetRow(rowindex).CreateCell(3);
                    if (ws.GetRow(rowindex).GetCell(4) == null) ws.GetRow(rowindex).CreateCell(4);
                    if (ws.GetRow(rowindex).GetCell(5) == null) ws.GetRow(rowindex).CreateCell(5);
                    if (ws.GetRow(rowindex).GetCell(6) == null) ws.GetRow(rowindex).CreateCell(6);
                    if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                    ws.GetRow(rowindex).GetCell(2).CellStyle = ws.GetRow(rowindex).GetCell(3).CellStyle = ws.GetRow(rowindex).GetCell(4).CellStyle = ws.GetRow(rowindex).GetCell(5).CellStyle = ws.GetRow(rowindex).GetCell(6).CellStyle = ws.GetRow(rowindex).GetCell(7).CellStyle = style1;
                    //Start
                    //if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                    //ws.GetRow(rowindex).GetCell(7).SetCellValue(itemSes.Start_Date != null ? itemSes.Start_Date.Value.ToString("dd.MM.yyyy") : "");
                    //ws.GetRow(rowindex).GetCell(7).CellStyle = style;
                    //End
                    //if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                    //ws.GetRow(rowindex).GetCell(8).SetCellValue(itemSes.End_Date != null ? itemSes.End_Date.Value.ToString("dd.MM.yyyy") : "");
                    //ws.GetRow(rowindex).GetCell(8).CellStyle = style;
                    //Budget(B)
                    if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                    ws.GetRow(rowindex).GetCell(8).SetCellValue(itemSes.Budget != null ? (double)itemSes.Budget.Value : 0);
                    ws.GetRow(rowindex).GetCell(8).CellStyle = styleQfw;
                    //Quotation(Q)
                    if (ws.GetRow(rowindex).GetCell(9) == null) ws.GetRow(rowindex).CreateCell(9);
                    ws.GetRow(rowindex).GetCell(9).SetCellValue(itemSes.Quotation != null ? (double)itemSes.Quotation.Value : 0);
                    ws.GetRow(rowindex).GetCell(9).CellStyle = styleQfw;
                    //Net value(N)
                    if (ws.GetRow(rowindex).GetCell(10) == null) ws.GetRow(rowindex).CreateCell(10);
                    ws.GetRow(rowindex).GetCell(10).SetCellValue(itemSes.Net_Value != null ? (double)itemSes.Net_Value.Value : 0);
                    ws.GetRow(rowindex).GetCell(10).CellStyle = styleQfw;
                    //Incl. Tax(V)
                    if (ws.GetRow(rowindex).GetCell(11) == null) ws.GetRow(rowindex).CreateCell(11);
                    ws.GetRow(rowindex).GetCell(11).SetCellValue(itemSes.Tax_Value != null ? (double)itemSes.Tax_Value.Value : 0);
                    ws.GetRow(rowindex).GetCell(11).CellStyle = styleQfw;
                    //Punishment(P)
                    if (ws.GetRow(rowindex).GetCell(12) == null) ws.GetRow(rowindex).CreateCell(12);
                    ws.GetRow(rowindex).GetCell(12).SetCellValue(itemSes.Punishment != null ? (double)itemSes.Punishment.Value : 0);
                    ws.GetRow(rowindex).GetCell(12).CellStyle = styleQfw;
                    //Deviation(N-B)
                    if (ws.GetRow(rowindex).GetCell(13) == null) ws.GetRow(rowindex).CreateCell(13);
                    decimal? dev = Funs.GetNewDecimal(itemSes.Deviation);
                    decimal? perc = Funs.GetNewDecimal(itemSes.By_Perc);
                    if (dev != null && dev >= 5000 && perc >= 30)
                    {
                        ws.GetRow(rowindex).GetCell(13).SetCellValue((double)dev);
                    }
                    else
                    {
                        ws.GetRow(rowindex).GetCell(13).SetCellValue("");
                    }
                    //ws.GetRow(rowindex).GetCell(14).SetCellValue(dev != null ? (double)dev : 0);
                    ws.GetRow(rowindex).GetCell(13).CellStyle = styleQfw;
                    //By perc.(N-B)/B
                    if (ws.GetRow(rowindex).GetCell(14) == null) ws.GetRow(rowindex).CreateCell(14);
                    if (perc != null && dev >= 5000 && perc >= 30)
                    {
                        ws.GetRow(rowindex).GetCell(14).SetCellValue(string.Format("{0:N}", perc) + "%");
                    }
                    else
                    {
                        ws.GetRow(rowindex).GetCell(14).SetCellValue("");
                    }
                    //ws.GetRow(rowindex).GetCell(15).SetCellValue(perc != null ? string.Format("{0:N}", perc * 100) + "%" : "");
                    ws.GetRow(rowindex).GetCell(14).CellStyle = styleQfw;
                    //Deduction(Q-V)
                    if (ws.GetRow(rowindex).GetCell(15) == null) ws.GetRow(rowindex).CreateCell(15);
                    decimal? dedu = Funs.GetNewDecimal(itemSes.Deduction);
                    ws.GetRow(rowindex).GetCell(15).SetCellValue(dedu != null ? (double)dedu : 0);
                    ws.GetRow(rowindex).GetCell(15).CellStyle = styleQfw;
                    //Con
                    if (ws.GetRow(rowindex).GetCell(16) == null) ws.GetRow(rowindex).CreateCell(16);
                    ws.GetRow(rowindex).GetCell(16).SetCellValue(itemSes.Con_Days != null ? itemSes.Con_Days.Value : 0);
                    ws.GetRow(rowindex).GetCell(16).CellStyle = style;
                    //BoQ
                    if (ws.GetRow(rowindex).GetCell(17) == null) ws.GetRow(rowindex).CreateCell(17);
                    ws.GetRow(rowindex).GetCell(17).SetCellValue(itemSes.BoQ_Days != null ? itemSes.BoQ_Days.Value : 0);
                    ws.GetRow(rowindex).GetCell(17).CellStyle = style;
                    //SES
                    if (ws.GetRow(rowindex).GetCell(18) == null) ws.GetRow(rowindex).CreateCell(18);
                    ws.GetRow(rowindex).GetCell(18).SetCellValue(itemSes.SES_Days != null ? itemSes.SES_Days.Value : 0);
                    ws.GetRow(rowindex).GetCell(18).CellStyle = style;
                    i++;
                    rowindex++;
                }
                //边框
                ICellStyle bankStyle = hssfworkbook.CreateCellStyle();
                bankStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                bankStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                bankStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                bankStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                bankStyle.Alignment = HorizontalAlignment.Left;
                bankStyle.VerticalAlignment = VerticalAlignment.Center;
                //背景色
                bankStyle.FillPattern = FillPattern.SolidForeground;
                bankStyle.FillForegroundColor = 23;
                if (ws.GetRow(rowindex) == null) ws.CreateRow(rowindex);
                if (ws.GetRow(rowindex + 1) == null) ws.CreateRow(rowindex + 1);
                ws.GetRow(rowindex).HeightInPoints = 19.8f;
                ws.GetRow(rowindex + 1).HeightInPoints = 19.8f;
                CellRangeAddress region = new CellRangeAddress(rowindex, rowindex, 2, 7);
                ws.AddMergedRegion(region);
                region = new CellRangeAddress(rowindex + 1, rowindex + 1, 2, 7);
                ws.AddMergedRegion(region);
                //region = new CellRangeAddress(rowindex, rowindex, 7, 8);
                //ws.AddMergedRegion(region);
                //region = new CellRangeAddress(rowindex + 1, rowindex + 1, 8, 9);
                //ws.AddMergedRegion(region);
                if (ws.GetRow(rowindex).GetCell(0) == null) ws.GetRow(rowindex).CreateCell(0);
                if (ws.GetRow(rowindex).GetCell(1) == null) ws.GetRow(rowindex).CreateCell(1);
                if (ws.GetRow(rowindex).GetCell(2) == null) ws.GetRow(rowindex).CreateCell(2);
                if (ws.GetRow(rowindex).GetCell(3) == null) ws.GetRow(rowindex).CreateCell(3);
                if (ws.GetRow(rowindex).GetCell(4) == null) ws.GetRow(rowindex).CreateCell(4);
                if (ws.GetRow(rowindex).GetCell(5) == null) ws.GetRow(rowindex).CreateCell(5);
                if (ws.GetRow(rowindex).GetCell(6) == null) ws.GetRow(rowindex).CreateCell(6);
                if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                ws.GetRow(rowindex).GetCell(0).CellStyle = ws.GetRow(rowindex).GetCell(1).CellStyle = ws.GetRow(rowindex).GetCell(2).CellStyle = ws.GetRow(rowindex).GetCell(3).CellStyle = ws.GetRow(rowindex).GetCell(4).CellStyle = ws.GetRow(rowindex).GetCell(5).CellStyle = ws.GetRow(rowindex).GetCell(6).CellStyle = ws.GetRow(rowindex).GetCell(7).CellStyle = style;
                //if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                //ws.GetRow(rowindex).GetCell(8).SetCellValue("Total Period");
                //ws.GetRow(rowindex).GetCell(8).CellStyle = bankStyle;
                //if (ws.GetRow(rowindex + 1).GetCell(7) == null) ws.GetRow(rowindex + 1).CreateCell(7);
                //ws.GetRow(rowindex + 1).GetCell(7).SetCellValue(sesSESList.Min(p => p.Start_Date) != null ? sesSESList.Min(p => p.Start_Date).Value.ToString("dd.MM.yyyy") : "");
                //ws.GetRow(rowindex + 1).GetCell(7).CellStyle = style;
                //if (ws.GetRow(rowindex + 1).GetCell(8) == null) ws.GetRow(rowindex + 1).CreateCell(8);
                //ws.GetRow(rowindex + 1).GetCell(8).SetCellValue(sesSESList.Max(p => p.End_Date) != null ? sesSESList.Max(p => p.End_Date).Value.ToString("dd.MM.yyyy") : "");
                //ws.GetRow(rowindex + 1).GetCell(8).CellStyle = style;
                if (ws.GetRow(rowindex + 1).GetCell(0) == null) ws.GetRow(rowindex + 1).CreateCell(0);
                if (ws.GetRow(rowindex + 1).GetCell(1) == null) ws.GetRow(rowindex + 1).CreateCell(1);
                if (ws.GetRow(rowindex + 1).GetCell(2) == null) ws.GetRow(rowindex + 1).CreateCell(2);
                if (ws.GetRow(rowindex + 1).GetCell(3) == null) ws.GetRow(rowindex + 1).CreateCell(3);
                if (ws.GetRow(rowindex + 1).GetCell(4) == null) ws.GetRow(rowindex + 1).CreateCell(4);
                if (ws.GetRow(rowindex + 1).GetCell(5) == null) ws.GetRow(rowindex + 1).CreateCell(5);
                if (ws.GetRow(rowindex + 1).GetCell(6) == null) ws.GetRow(rowindex + 1).CreateCell(6);
                if (ws.GetRow(rowindex + 1).GetCell(7) == null) ws.GetRow(rowindex + 1).CreateCell(7);
                //if (ws.GetRow(rowindex + 1).GetCell(8) == null) ws.GetRow(rowindex + 1).CreateCell(8);
                //if (ws.GetRow(rowindex + 1).GetCell(9) == null) ws.GetRow(rowindex + 1).CreateCell(9);
                ws.GetRow(rowindex + 1).GetCell(0).CellStyle = ws.GetRow(rowindex + 1).GetCell(1).CellStyle = ws.GetRow(rowindex + 1).GetCell(2).CellStyle = ws.GetRow(rowindex + 1).GetCell(3).CellStyle = ws.GetRow(rowindex + 1).GetCell(4).CellStyle = ws.GetRow(rowindex + 1).GetCell(5).CellStyle = ws.GetRow(rowindex + 1).GetCell(6).CellStyle = ws.GetRow(rowindex + 1).GetCell(7).CellStyle = style;
                region = new CellRangeAddress(rowindex, rowindex, 8, 12);
                ws.AddMergedRegion(region);
                if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                ws.GetRow(rowindex).GetCell(8).SetCellValue("Total:");
                ws.GetRow(rowindex).GetCell(8).CellStyle = bankStyle;
                if (ws.GetRow(rowindex + 1).GetCell(8) == null) ws.GetRow(rowindex + 1).CreateCell(8);
                ws.GetRow(rowindex + 1).GetCell(8).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? (double)sesSESList.Sum(p => p.Budget).Value : 0);
                ws.GetRow(rowindex + 1).GetCell(8).CellStyle = styleQfw;
                if (ws.GetRow(rowindex + 1).GetCell(9) == null) ws.GetRow(rowindex + 1).CreateCell(9);
                ws.GetRow(rowindex + 1).GetCell(9).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? (double)sesSESList.Sum(p => p.Quotation).Value : 0);
                ws.GetRow(rowindex + 1).GetCell(9).CellStyle = styleQfw;
                if (ws.GetRow(rowindex + 1).GetCell(10) == null) ws.GetRow(rowindex + 1).CreateCell(10);
                ws.GetRow(rowindex + 1).GetCell(10).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? (double)sesSESList.Sum(p => p.Net_Value).Value : 0);
                ws.GetRow(rowindex + 1).GetCell(10).CellStyle = styleQfw;
                if (ws.GetRow(rowindex + 1).GetCell(11) == null) ws.GetRow(rowindex + 1).CreateCell(11);
                ws.GetRow(rowindex + 1).GetCell(11).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? (double)sesSESList.Sum(p => p.Tax_Value).Value : 0);
                ws.GetRow(rowindex + 1).GetCell(11).CellStyle = styleQfw;
                if (ws.GetRow(rowindex + 1).GetCell(12) == null) ws.GetRow(rowindex + 1).CreateCell(12);
                ws.GetRow(rowindex + 1).GetCell(12).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? (double)sesSESList.Sum(p => p.Punishment).Value : 0);
                ws.GetRow(rowindex + 1).GetCell(12).CellStyle = styleQfw;
                if (ws.GetRow(rowindex).GetCell(13) == null) ws.GetRow(rowindex).CreateCell(13);
                if (ws.GetRow(rowindex).GetCell(14) == null) ws.GetRow(rowindex).CreateCell(14);
                ws.GetRow(rowindex).GetCell(13).CellStyle = ws.GetRow(rowindex).GetCell(14).CellStyle = bankStyle;
                if (ws.GetRow(rowindex).GetCell(15) == null) ws.GetRow(rowindex).CreateCell(15);
                ws.GetRow(rowindex).GetCell(15).SetCellValue("Total:");
                ws.GetRow(rowindex).GetCell(15).CellStyle = bankStyle;
                if (ws.GetRow(rowindex + 1).GetCell(13) == null) ws.GetRow(rowindex + 1).CreateCell(13);
                if (ws.GetRow(rowindex + 1).GetCell(14) == null) ws.GetRow(rowindex + 1).CreateCell(14);
                ws.GetRow(rowindex + 1).GetCell(13).CellStyle = ws.GetRow(rowindex + 1).GetCell(14).CellStyle = style;
                if (ws.GetRow(rowindex + 1).GetCell(15) == null) ws.GetRow(rowindex + 1).CreateCell(15);
                ws.GetRow(rowindex + 1).GetCell(15).SetCellValue((double)sesSESList.Sum(p => double.Parse(p.Deduction)));
                ws.GetRow(rowindex + 1).GetCell(15).CellStyle = styleQfw;
                region = new CellRangeAddress(rowindex, rowindex, 16, 18);
                ws.AddMergedRegion(region);
                if (ws.GetRow(rowindex).GetCell(16) == null) ws.GetRow(rowindex).CreateCell(16);
                ws.GetRow(rowindex).GetCell(16).SetCellValue("Average:");
                ws.GetRow(rowindex).GetCell(16).CellStyle = bankStyle;
                if (ws.GetRow(rowindex + 1).GetCell(16) == null) ws.GetRow(rowindex + 1).CreateCell(16);
                ws.GetRow(rowindex + 1).GetCell(16).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? Math.Round(sesSESList.Average(p => p.Con_Days != null && p.Con_Days >= 0 ? p.Con_Days : 0).Value, 0) : 0);
                ws.GetRow(rowindex + 1).GetCell(16).CellStyle = style;
                if (ws.GetRow(rowindex + 1).GetCell(17) == null) ws.GetRow(rowindex + 1).CreateCell(17);
                ws.GetRow(rowindex + 1).GetCell(17).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? Math.Round(sesSESList.Average(p => p.BoQ_Days != null && p.BoQ_Days >= 0 ? p.BoQ_Days : 0).Value, 0) : 0);
                ws.GetRow(rowindex + 1).GetCell(17).CellStyle = style;
                if (ws.GetRow(rowindex + 1).GetCell(18) == null) ws.GetRow(rowindex + 1).CreateCell(18);
                ws.GetRow(rowindex + 1).GetCell(18).SetCellValue(sesSESList != null && sesSESList.Count() > 0 ? Math.Round(sesSESList.Average(p => p.SES_Days != null && p.SES_Days >= 0 ? p.SES_Days : 0).Value, 0) : 0);
                ws.GetRow(rowindex + 1).GetCell(18).CellStyle = style;
                #endregion
                ws.ForceFormulaRecalculation = true;
                using (FileStream filess = File.OpenWrite(ReportFileName))
                {
                    hssfworkbook.Write(filess);
                }
                FileInfo filet = new FileInfo(ReportFileName);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(cptNo) + ".xlsx");
                // 添加头信息,指定文件大小,让浏览器能够显示下载进度
                Response.AddHeader("Content-Length", filet.Length.ToString());
                // 指定返回的是一个不能被客户端读取的流,必须被下载
                Response.ContentType = "application/ms-excel";
                // 把文件流发送到客户端
                Response.WriteFile(filet.FullName);
                // 停止页面的执行
                Response.End();
            }
        }
        protected void btnNoCpt_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //模板文件
            string TempletFileName = rootPath + "SES_without_CPT.xlsx";
            //导出文件
            string filePath = rootPath + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string ReportFileName = filePath + "out.xls";
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
            XSSFSheet ws = (XSSFSheet)hssfworkbook.GetSheetAt(0);
            string strSql = @"SELECT FO,SES_No FROM dbo.FC_SESReport 
                              WHERE (Accepted='X' OR Accepted='x') 
                                           AND SES_No NOT IN (SELECT ses FROM dbo.SESList)
                              ORDER BY FO,SES_No";
            DataTable dt = SQLHelper.GetDataTableRunText(strSql, null);
            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    if (ws.GetRow(i) == null) ws.CreateRow(i);
                    if (ws.GetRow(i).GetCell(0) == null) ws.GetRow(i).CreateCell(0);
                    ws.GetRow(i).GetCell(0).SetCellValue(dt.Rows[i-1]["FO"].ToString());
                    if (ws.GetRow(i).GetCell(1) == null) ws.GetRow(i).CreateCell(1);
                    ws.GetRow(i).GetCell(1).SetCellValue(dt.Rows[i-1]["SES_No"].ToString());
                }
               
            }
            ws.ForceFormulaRecalculation = true;
            using (FileStream filess = File.OpenWrite(ReportFileName))
            {
                hssfworkbook.Write(filess);
            }
            FileInfo filet = new FileInfo(ReportFileName);
            Response.Clear();
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
            Response.AddHeader("Content-Disposition", "attachment; filename=SES_without_CPT_" + Server.UrlEncode(DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx"));
            // 添加头信息,指定文件大小,让浏览器能够显示下载进度
            Response.AddHeader("Content-Length", filet.Length.ToString());
            // 指定返回的是一个不能被客户端读取的流,必须被下载
            Response.ContentType = "application/ms-excel";
            // 把文件流发送到客户端
            Response.WriteFile(filet.FullName);
            // 停止页面的执行
            Response.End();
        }
        #endregion
        #region 时间间隔
        /// 
        /// 时间间隔
        /// 
        /// 开始时间
        /// 结束时间
        /// 返回类型1:天2:小时3:分钟4:秒数
        /// 
        private int GetTimeSpan(DateTime startTime, DateTime endTime, int timeType = 1)
        {
            if (startTime > endTime)
            {
                return 0;
            }
            TimeSpan ts = endTime - startTime;
            return timeType == 1 ? ts.Days : timeType == 2 ? ts.Hours : timeType == 3 ? ts.Minutes : ts.Seconds;
        }
        #endregion
    }
}