using System; using System.Data; using System.Collections.Generic; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Data; using DSWeb.Areas.CommMng.Models; using DSWeb.EntityDA; using HcUtility.Comm; using DSWeb.MvcShipping.DAL.MsSysParamSet; using System.Linq; using DSWeb.MvcShipping.Models.MsChFeeYsAutoDui; using DSWeb.TruckMng.Helper; using DSWeb.Areas.CommMng.DAL; using DSWeb.MvcShipping.Models.WMSNew; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; using NPOI.SS.Util; //using System.Net.Mail; //using System.Net.Mime; //using System.Net; using MailKit.Net.Smtp; using MimeKit; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Checksum; using DSWeb.MvcShipping.DAL.MsSysBillNoSet; using System.Data.SqlClient; using DSWeb.MvcShipping.Models.MsOpMailLog; using HcUtility.Core; using MimeKit.Utils; using CommonTool.MailKit; namespace DSWeb.MvcShipping.DAL.MsChFeeYsAutoDui { public class MsChFeeYsAutoDuiDAL { private static string _ComName = ""; private static string _UserId = ""; private static string _email = ""; public static List GetDataList(string strCondition, int start, int limit, out int count, string sort) { var strSql = new StringBuilder(); strSql.Append(@"SELECT SUM(CASE WHEN (c.ISINVOICE=0 OR c.ISINVOICE IS NULL) AND c.FEETYPE=1 THEN ISNULL(c.INVOICE,0) * ISNULL(c.EXCHANGERATE,0) ELSE 0 END) TTLINVDR, SUM(CASE WHEN (c.ISINVOICE=0 OR c.ISINVOICE IS NULL) AND c.FEETYPE=1 THEN ISNULL(c.AMOUNT,0) * ISNULL(c.EXCHANGERATE,0) ELSE 0 END) TTLDR , C.CUSTOMERNAME KeHuJianCheng, IC.DESCRIPTION KeHuQuanCheng, '' LanHuoRen, CD.DUIDATE DuiZhangRiQi, IC.CHIEF DuiZhangLianXiRen, IC.TEL DuiZhangLianXiDianHua, isnull(stuff ((SELECT distinct EMAIL+';' FROM info_client_contact AS t WHERE ISNULL(ISDUI,0)=1 AND LINKID=IC.GID FOR xml path('')), 1, 0, ''),IC.EMAIL) DuiZhangLianXiYouXiang, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouUSD, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuUSD, --查询字段 CD.OP DuiZhangRen, CD.DUINO DuiZhangBianHao, CD.DUINAME DuiZhangMingCheng, CD.REMARKS DuiZhangBeiZhu, (SELECT TOP 1 ACCTYPE FROM Info_Client_ACCDATE WHERE LINKGID=IC.GID ORDER BY BGNDATE DESC) JieFeiLeiXing FROM ch_fee C LEFT JOIN ch_dui CD on CD.DUINO = C.DEBITNO LEFT JOIN info_client IC on IC.SHORTNAME = C.CUSTOMERNAME WHERE 1=1 "); if (!string.IsNullOrEmpty(strCondition)) { strSql.Append(" " + strCondition); } strSql.Append(@" GROUP BY C.CUSTOMERNAME,IC.DESCRIPTION,IC.CHIEF,IC.TEL,IC.EMAIL,CD.OP,CD.DUINO,CD.DUINAME,CD.REMARKS,CD.DUIDATE,IC.GID "); if (!string.IsNullOrEmpty(sort)) { var so = JsonConvert.Deserialize>(sort); string orderbyStr = " ORDER BY "; foreach (var s in so) { orderbyStr += s.property + " " + s.direction + ","; } orderbyStr = orderbyStr.Substring(0, orderbyStr.Length - 1); strSql.Append(orderbyStr); } else { strSql.Append(" order by C.CUSTOMERNAME "); } int totalCount = 0; StringBuilder sb = PagerHelper.PageSQL(strSql.ToString(), start, limit, out totalCount); count = totalCount; return SetData(sb); } private static List SetData(StringBuilder sb) { var headList = new List(); Database db = DatabaseFactory.CreateDatabase(); using (IDataReader reader = db.ExecuteReader(CommandType.Text, sb.ToString())) { while (reader.Read()) { MsChFeeYsAutoDuiModel data = new MsChFeeYsAutoDuiModel(); #region Set DB data to Object data.KeHuJianCheng = reader["KeHuJianCheng"].ToString(); data.KeHuQuanCheng = reader["KeHuQuanCheng"].ToString(); data.LanHuoRen = reader["LanHuoRen"].ToString(); data.YingShouRMB = reader["YingShouRMB"].ToString(); data.YingShouUSD = reader["YingShouUSD"].ToString(); data.YingFuRMB = reader["YingFuRMB"].ToString(); data.YingFuUSD = reader["YingFuUSD"].ToString(); data.DuiZhangLianXiRen = reader["DuiZhangLianXiRen"].ToString(); data.DuiZhangLianXiYouXiang = reader["DuiZhangLianXiYouXiang"].ToString(); data.DuiZhangLianXiDianHua = reader["DuiZhangLianXiDianHua"].ToString(); data.DuiZhangBeiZhu = reader["DuiZhangBeiZhu"].ToString(); data.DuiZhangRiQi = reader["DuiZhangRiQi"].ToString(); data.JieFeiLeiXing = reader["JieFeiLeiXing"].ToString(); data.DuiZhangBianHao = reader["DuiZhangBianHao"].ToString(); //data.YiJieSuan = reader["YiJieSuan"].ToString(); //data.JieFeiLeiXing = reader["JieFeiLeiXing"].ToString(); //data.ZhangQi = reader["ZhangQi"].ToString(); //data.YingJieRiQi = reader["YingJieRiQi"].ToString(); //data.YouXiangRiQi = reader["YouXiangRiQi"].ToString(); //data.YouJianYiFaSong = reader["YouJianYiFaSong"].ToString(); decimal ttldr = 0; if (reader["TTLDR"] != DBNull.Value) ttldr = Convert.ToDecimal(reader["TTLDR"]); decimal ttlinvdr = 0; if (reader["TTLDR"] != DBNull.Value) ttlinvdr = Convert.ToDecimal(reader["TTLINVDR"]); if (ttlinvdr == 0) data.YingShouKaiPiao = "未开票"; else if (ttlinvdr == ttldr) data.YingShouKaiPiao = "已开票"; else if (ttlinvdr != ttldr) data.YingShouKaiPiao = "部分开票"; #endregion headList.Add(data); } reader.Close(); } return headList; } public static string GetRangDAStr(string tb, string userid, string username, string companyid) { string str = ""; var strSql = new StringBuilder(); strSql.Append("SELECT "); strSql.Append(" VISIBLERANGE,OPERATERANGE,AUTHORITYID,VSSQL "); strSql.Append(" from VW_User_Authority "); strSql.Append(" where [NAME]='modChDuiFeeList' and USERID='" + userid + "' and ISDELETE=0"); string visiblerange = "4"; string operaterange = "4"; string AUTHORITYID = ""; string VSSQL = ""; Database db = DatabaseFactory.CreateDatabase(); using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString())) { while (reader.Read()) { visiblerange = Convert.ToString(reader["VISIBLERANGE"]); operaterange = Convert.ToString(reader["OPERATERANGE"]); AUTHORITYID = Convert.ToString(reader["AUTHORITYID"]); VSSQL = Convert.ToString(reader["VSSQL"]); break; } reader.Close(); } if (visiblerange == "4") { str = " (duiOp='" + username /*+ "' OR INPUTBY='" + username*/ + "')"; } else if (visiblerange == "3") { str = " (duiOp='" + username /*+ "' OR INPUTBY='" + username*/ + "')"; } else if (visiblerange == "2") { var rangeDa = new RangeDA(); var deptname = rangeDa.GetDEPTNAME(userid); str = " (duiOp in (select showname from [user] where GID in (select USERID from user_company where COMPANYID=(select GID from [company] where codename='" + companyid + "')) and GID in (select userid from user_baseinfo where DEPTNAME='" + deptname + "')))"; //+ " OR INPUTBY in (select showname from [user] where GID in (select USERID from user_company where COMPANYID='" + companyid + "') and GID in (select userid from user_baseinfo where DEPTNAME='" + deptname + "')))"; } else if (visiblerange == "1") { str = " (duiOp in (select showname from [user] where GID in (select USERID from user_company where COMPANYID=(select GID from [company] where codename='" + companyid + "'))))"; //+ " OR INPUTBY in (select showname from [user] where GID in (select USERID from user_company where COMPANYID='" + companyid + "')))"; } else if (visiblerange == "5") { str = " (duiOp in (select showname from [user] where GID in (select USERID from user_company where COMPANYID IN (select COMPANYID from user_authority_range_company where userid='" + userid + "' and AUTHORITYID='" + AUTHORITYID + "' and VISIBLERANGE=1))))"; //var userstr = new StringBuilder(); //userstr.Append(" select COMPANYID from user_authority_range_company where userid='" + userid + "' and AUTHORITYID='" + AUTHORITYID + "' and VISIBLERANGE=1"); //Database userdb = DatabaseFactory.CreateDatabase(); //using (IDataReader reader = userdb.ExecuteReader(CommandType.Text, userstr.ToString())) //{ // str = ""; // while (reader.Read()) // { // if (str == "") // { // str = " (COMPANYID='" + Convert.ToString(reader["COMPANYID"]) + "'"; // } // else // { // str = str + " or COMPANYID='" + Convert.ToString(reader["COMPANYID"]) + "'"; // }; // } // str = str + ")"; // reader.Close(); //} } else if (visiblerange == "6") { var userstr = new StringBuilder(); userstr.Append(" select OPID,(select SHOWNAME from [user] where GID=user_authority_range_op.OPID) SHOWNAME from user_authority_range_op where userid='" + userid + "' and AUTHORITYID='" + AUTHORITYID + "' and VISIBLERANGE=1"); Database userdb = DatabaseFactory.CreateDatabase(); using (IDataReader reader = userdb.ExecuteReader(CommandType.Text, userstr.ToString())) { str = ""; while (reader.Read()) { if (str == "") { str = " (duiOp='" + Convert.ToString(reader["SHOWNAME"]) + "'"; } else { str = str + " or duiOp='" + Convert.ToString(reader["SHOWNAME"]) + "'"; }; } str = str + ")"; reader.Close(); } } else if (visiblerange == "0") { str = " 1=1 "; } VSSQL = VSSQL.Trim(); if (!string.IsNullOrEmpty(VSSQL)) { if (!string.IsNullOrEmpty(str)) { str = str + " and (" + VSSQL + ") "; } else { str = " (" + VSSQL + ") "; } } return str; } public static List GetMainDataList(string strCondition, int start, int limit, string userid, string usercode, string orgcode, out int count, string sort) { var rangstr = GetRangDAStr("", userid, usercode, orgcode); if (!string.IsNullOrEmpty(rangstr)) { if (!string.IsNullOrEmpty(strCondition)) { strCondition = strCondition + " and " + rangstr; } else { strCondition = rangstr; } } var strSql = new StringBuilder(); strSql.Append(@"SELECT * FROM CH_DUI_MAIN WHERE 1=1 "); if (!string.IsNullOrEmpty(strCondition)) { strSql.Append(" and " + strCondition); } if (!string.IsNullOrEmpty(sort)) { var so = JsonConvert.Deserialize>(sort); string orderbyStr = " ORDER BY "; foreach (var s in so) { orderbyStr += s.property + " " + s.direction + ","; } orderbyStr = orderbyStr.Substring(0, orderbyStr.Length - 1); strSql.Append(orderbyStr); } else { strSql.Append(" order by mainDuiNo desc "); } int totalCount = 0; StringBuilder sb = PagerHelper.PageSQL(strSql.ToString(), start, limit, out totalCount); count = totalCount; return SetMainData(sb); } private static List SetMainData(StringBuilder sb) { var headList = new List(); Database db = DatabaseFactory.CreateDatabase(); using (IDataReader reader = db.ExecuteReader(CommandType.Text, sb.ToString())) { while (reader.Read()) { MsChFeeYsAutoDuiMainModel data = new MsChFeeYsAutoDuiMainModel(); #region Set DB data to Object data.dMainId = reader["dMainId"].ToString(); data.mainDuiNo = reader["mainDuiNo"].ToString(); data.mainDuiName = reader["mainDuiName"].ToString(); data.duiOp = reader["duiOp"].ToString(); data.description = reader["description"].ToString(); if (reader["duiDate"] != DBNull.Value) { DateTime duidt = DateTime.Parse(reader["duiDate"].ToString()); data.duiDate = duidt.ToString("yyyy-MM-dd"); } data.createDate = reader["createDate"].ToString(); if (reader["KaiChuanRiFrom"] != DBNull.Value) { DateTime KaiChuanRiFrom = DateTime.Parse(reader["KaiChuanRiFrom"].ToString()); data.KaiChuanRiFrom = KaiChuanRiFrom.ToString("yyyy-MM-dd"); } if (reader["KaiChuanRiTo"] != DBNull.Value) { DateTime KaiChuanRiTo = DateTime.Parse(reader["KaiChuanRiTo"].ToString()); data.KaiChuanRiTo = KaiChuanRiTo.ToString("yyyy-MM-dd"); } data.DuiZhangKeHu = reader["DuiZhangKeHu"].ToString(); data.ShouFuFangXiang = reader["ShouFuFangXiang"].ToString(); data.JieFeiLeiXing = reader["JieFeiLeiXing"].ToString(); data.ShiFouYiKaiPiao = reader["ShiFouYiKaiPiao"].ToString(); data.FeiYongZhuangTai = reader["FeiYongZhuangTai"].ToString(); data.accDate_Min = reader["accDate_Min"].ToString(); data.accDate_Max = reader["accDate_Max"].ToString(); data.SALECORPID= reader["SALECORPID"].ToString(); data.CORPID = reader["CORPID"].ToString(); data.BiBie = reader["BiBie"].ToString(); data.FEENAME = reader["FEENAME"].ToString(); if (reader["ISCHAOQI"] != DBNull.Value) data.ISCHAOQI = reader["ISCHAOQI"].ToString(); if (reader["ISZHIQI"] != DBNull.Value) data.ISZHIQI = reader["ISZHIQI"].ToString(); if (reader["EXCHANGERATE"] != DBNull.Value) data.EXCHANGERATE =reader["EXCHANGERATE"].ToString(); #endregion headList.Add(data); } reader.Close(); } return headList; } public static List GetDetailsList(string conditions) { if (conditions != "") { conditions = " " + conditions; } string sql = string.Format(@"select VB.BSTYPE as YeWuLeiXing, VB.BLTYPE as ZhuangYunFangShi, VB.CUSTNO as WeiTuoBianHao, VB.MBLNO as ZhuTiDanHao , VB.HBLNO as FenTiDanHao, VB.ETD as KaiChuanRiQi, VB.VESSEL as ChuanMing, VB.VOYNO as HangCi, VB.CNTRTOTAL as JiZhuangXiang, VB.SALE as LanHuoRen, VB.OP as CaoZuo, VB.DOC as DanZheng, VB.LANE as HangXian, VB.CUSTSERVICE as KeFu, VB.PORTLOAD as ZhuangHuoGang, VB.PORTDISCHARGE as XieHuoGang, MAX(C.SALECORP) SALECORP, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouUSD, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuUSD from ch_fee C left join v_op_bill VB on C.BSNO = VB.BSNO where 1=1 {0} GROUP BY VB.BSTYPE,VB.BLTYPE ,VB.CUSTNO,VB.MBLNO ,VB.HBLNO,VB.ETD,VB.VESSEL,VB.VOYNO,VB.CNTRTOTAL,VB.SALE,VB.OP,VB.DOC,VB.LANE ,VB.CUSTSERVICE,VB.PORTLOAD,VB.PORTDISCHARGE order by VB.MBLNO", conditions); return SetDetailsData(sql); } private static List SetDetailsData(string sql) { var headList = new List(); Database db = DatabaseFactory.CreateDatabase(); using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql)) { while (reader.Read()) { MsChFeeYsAutoDuiDetailsModel data = new MsChFeeYsAutoDuiDetailsModel(); #region Set DB data to Object data.YeWuLeiXing = reader["YeWuLeiXing"].ToString(); data.ZhuangYunFangShi = reader["ZhuangYunFangShi"].ToString(); data.WeiTuoBianHao = reader["WeiTuoBianHao"].ToString(); data.ZhuTiDanHao = reader["ZhuTiDanHao"].ToString(); data.FenTiDanHao = reader["FenTiDanHao"].ToString(); if (reader["KaiChuanRiQi"] != DBNull.Value) { DateTime etdDate = DateTime.Parse(reader["KaiChuanRiQi"].ToString()); data.KaiChuanRiQi = etdDate.ToString("yyyy-MM-dd"); } data.ChuanMing = reader["ChuanMing"].ToString(); data.HangCi = reader["HangCi"].ToString(); data.JiZhuangXiang = reader["JiZhuangXiang"].ToString(); data.LanHuoRen = reader["LanHuoRen"].ToString(); data.CaoZuo = reader["CaoZuo"].ToString(); data.DanZheng = reader["DanZheng"].ToString(); data.HangXian = reader["HangXian"].ToString(); data.KeFu = reader["KeFu"].ToString(); data.ZhuangHuoGang = reader["ZhuangHuoGang"].ToString(); data.XieHuoGang = reader["XieHuoGang"].ToString(); data.YingShouRMB = reader["YingShouRMB"].ToString(); data.YingShouUSD = reader["YingShouUSD"].ToString(); //data.YingShouQiTa = reader["YingShouQiTa"].ToString(); data.YingFuRMB = reader["YingFuRMB"].ToString(); data.YingFuUSD = reader["YingFuUSD"].ToString(); data.SALECORP= reader["SALECORP"].ToString(); #endregion headList.Add(data); } reader.Close(); } return headList; } private static List GetExcelDataList(string conditions) { if (conditions != "") { conditions = " and " + conditions; } string sql = string.Format(@" select VB.MBLNO, C.CUSTOMERNAME, VB.VESSEL, VB.VOYNO, VB.ETD, VB.OP, VB.SALE, VB.DESTINATION, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) SRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) SUSD, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) FRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) FUSD, C.DebitNo, max(c.SALECORP) SALECORP from ch_fee C left join v_op_bill VB on C.BSNO = VB.BSNO where 1=1 {0} GROUP BY VB.MBLNO,VB.VESSEL,VB.VOYNO,VB.ETD,VB.OP,VB.SALE,VB.DESTINATION, C.CUSTOMERNAME,C.DebitNo order by C.CUSTOMERNAME,VB.MBLNO ",conditions); return SetExcelData(sql); } private static List GetExcelNODAYDataList(string conditions,string ISZHIQI, decimal EXCHANGERATE=0) { if (conditions != "") { conditions = " and " + conditions; } string sql = string.Format(@" select *,(SRMB+SUSD*{0})*NODAY*0.005 NOAMOUNT from (select VB.MBLNO, C.CUSTOMERNAME, VB.VESSEL, VB.VOYNO, VB.ETD, VB.OP, VB.SALE, VB.DESTINATION, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) SRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) SUSD, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) FRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) FUSD, C.DebitNo, DATEDIFF([day],[dbo].[GetCustStlDay](VB.ETD,C.CUSTOMERNAME,VB.SALE),GETDATE()) NODAY, max(c.SALECORP) SALECORP from ch_fee C left join v_op_bill VB on C.BSNO = VB.BSNO where 1=1 {1} GROUP BY VB.MBLNO,VB.VESSEL,VB.VOYNO,VB.ETD,VB.OP,VB.SALE,VB.DESTINATION, C.CUSTOMERNAME,C.DebitNo ) as VS order by CUSTOMERNAME,MBLNO", EXCHANGERATE.ToString(), conditions); return SetExcelNODAYData(sql); } private static List SetExcelData(string sql) { var headList = new List(); Database db = DatabaseFactory.CreateDatabase(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql.ToString(); cmd.CommandTimeout = 120000; //要加这一句 using (IDataReader reader = db.ExecuteReader(cmd)) { while (reader.Read()) { MsChFeeYsAutoDuiExcelModel data = new MsChFeeYsAutoDuiExcelModel(); #region Set DB data to Object data.KeHuMingCheng = reader["CUSTOMERNAME"].ToString(); data.MBLNO = reader["MBLNO"].ToString(); data.ChuanMing = reader["VESSEL"].ToString(); data.HangCi = reader["VOYNO"].ToString(); data.OP = reader["OP"].ToString(); data.SALE = reader["SALE"].ToString(); data.KaiChuanRi = reader["ETD"].ToString(); data.MuDiGang = reader["DESTINATION"].ToString(); data.RMB = reader["SRMB"].ToString(); data.USD = reader["SUSD"].ToString(); data.FRMB = reader["FRMB"].ToString(); data.FUSD = reader["FUSD"].ToString(); data.DuiNo = reader["DebitNo"].ToString(); data.NOAMOUNT ="0"; data.SALECORP = reader["SALECORP"].ToString(); #endregion headList.Add(data); } reader.Close(); } return headList; } private static List SetExcelNODAYData(string sql) { var headList = new List(); Database db = DatabaseFactory.CreateDatabase(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql.ToString(); cmd.CommandTimeout = 120000; //要加这一句 using (IDataReader reader = db.ExecuteReader(cmd)) { while (reader.Read()) { MsChFeeYsAutoDuiExcelModel data = new MsChFeeYsAutoDuiExcelModel(); #region Set DB data to Object data.KeHuMingCheng = reader["CUSTOMERNAME"].ToString(); data.MBLNO = reader["MBLNO"].ToString(); data.ChuanMing = reader["VESSEL"].ToString(); data.HangCi = reader["VOYNO"].ToString(); data.OP = reader["OP"].ToString(); data.SALE = reader["SALE"].ToString(); data.KaiChuanRi = reader["ETD"].ToString(); data.MuDiGang = reader["DESTINATION"].ToString(); data.RMB = reader["SRMB"].ToString(); data.USD = reader["SUSD"].ToString(); data.FRMB = reader["FRMB"].ToString(); data.FUSD = reader["FUSD"].ToString(); data.DuiNo = reader["DebitNo"].ToString(); data.NODAY = reader["NODAY"].ToString(); data.NOAMOUNT = reader["NOAMOUNT"].ToString(); data.SALECORP = reader["SALECORP"].ToString(); #endregion headList.Add(data); } reader.Close(); } return headList; } public static DBResult SendExcel(List list, string path, string userid, string comid,string cc, out string datapath,DSWeb.SoftMng.Model.EmailConfig model,string username,string useduiname, string ISZHIQI="0", decimal EXCHANGERATE = 0, string ISCHAOQI = "0") { var result = new DBResult(); try { string DataPath = ""; _UserId = userid; string UserName = GetUserNameWithUserId(userid); string ComName = GetComNameWithComId(comid); string mainduiname = ""; if (list.Count>0) { mainduiname = GetDuiNameWithDuiNo(list[0].DuiZhangBianHao); } _ComName = ComName; //获取数据 string whereSql = ""; string custStr = ""; foreach (var item in list) { custStr += "'" + item.DuiZhangBianHao + "',"; } custStr = custStr.Substring(0, custStr.Length - 1); whereSql = "C.DEBITNO IN (" + custStr + ") "; List excelList = new List(); if (ISZHIQI=="1") excelList=GetExcelNODAYDataList(whereSql, ISZHIQI, EXCHANGERATE); else excelList=GetExcelDataList(whereSql); //遍历list,每个客户生成一个excel并发送 string tempCust = ""; foreach (var item in excelList) { if (tempCust == item.KeHuMingCheng) { continue; } if (item.KeHuMingCheng != tempCust) { tempCust = item.KeHuMingCheng; List listSend = excelList.FindAll(e => e.KeHuMingCheng == tempCust); //生成excel string filename = ""; var YSAUTODUIISNOTSALEOP=MsSysParamSetDAL.GetData("PARAMNAME='YSAUTODUIISNOTSALEOP'").PARAMVALUE; if (YSAUTODUIISNOTSALEOP == "1") DataPath = ListToExcelNoOpSale(listSend, path, UserName, ComName, out filename, mainduiname, useduiname); else { if (ISZHIQI == "1") DataPath = ListToExcelNoDay(listSend, path, UserName, ComName, out filename, mainduiname, useduiname, EXCHANGERATE,ISCHAOQI); else DataPath = ListToExcel(listSend, path, UserName, ComName, out filename, mainduiname, useduiname, ISCHAOQI); } if (DataPath == "") { datapath = ""; result.Success = false; result.Message = "生成EXCEL错误!"; return result; } //发送邮件 //获取邮件地址 string email = list.Find(f => f.KeHuJianCheng == tempCust).DuiZhangLianXiYouXiang; //设置邮件内容 string title = DateTime.Now.ToString("yyyy-MM") + tempCust + "客户对账单"; if (useduiname == "1") title = mainduiname; string sign = GetSign(userid); string context = sign; //发送 //if (cc != "1") _email = ""; // string[] emailList = email.Split(';'); //foreach (var m in emailList) //{ // if (m!="") // { result=SendMailWithExcelFile(title, context, DataPath, email, _email, _ComName, tempCust, model,username, cc); // } //} //if (_email!=""&&cc=="1") SendMailWithExcelFile(title, context, DataPath, _email, _ComName, tempCust, model, username); } } datapath = DataPath; } catch (Exception e) { datapath = ""; result.Success = false; result.Message = e.Message; return result; } return result; } /// /// 返回excel文件路径 /// /// /// /// /// /// /// /// public static string GetExcelUrls(List list, string path, string userid, string comid, string timeStr, string condition, string useduiname, string ISZHIQI ="0", decimal EXCHANGERATE = 0, string ISCHAOQI = "0") { try { string DataPath = ""; _UserId = userid; string UserName = GetUserNameWithUserId(userid); string ComName = GetComNameWithComId(comid); string mainduiname = ""; if (list.Count > 0) { mainduiname = GetDuiNameWithDuiNo(list[0].DuiZhangBianHao); } _ComName = ComName; //获取数据 string whereSql = ""; string custStr = ""; foreach (var item in list) { custStr += "'" + item.DuiZhangBianHao + "',"; } custStr = custStr.Substring(0, custStr.Length - 1); whereSql = "C.DEBITNO IN (" + custStr + ") "; if (!string.IsNullOrEmpty(condition)) { whereSql = condition+ " and "+ whereSql; } List excelList = new List(); if (ISZHIQI == "1") excelList = GetExcelNODAYDataList(whereSql, ISZHIQI, EXCHANGERATE); else excelList = GetExcelDataList(whereSql); string tempCust = ""; foreach (var item in excelList) { if (tempCust == item.KeHuMingCheng) { continue; } if (item.KeHuMingCheng != tempCust) { tempCust = item.KeHuMingCheng; List listSend = excelList.FindAll(e => e.KeHuMingCheng == tempCust); //生成excel string filename = ""; var YSAUTODUIISNOTSALEOP = MsSysParamSetDAL.GetData("PARAMNAME='YSAUTODUIISNOTSALEOP'").PARAMVALUE; if (YSAUTODUIISNOTSALEOP == "1") DataPath = ListToExcelNoOpSale(listSend, path + "\\Excels\\", UserName, ComName, out filename, mainduiname, useduiname); else { if (ISZHIQI == "1") DataPath = ListToExcelNoDay(listSend, path + "\\Excels\\", UserName, ComName, out filename, mainduiname, useduiname, EXCHANGERATE, ISCHAOQI); else DataPath = ListToExcel(listSend, path + "\\Excels\\", UserName, ComName, out filename, mainduiname, useduiname, ISCHAOQI); } } } // CreateZipFile(path+"\\Excels\\",path+"\\zip\\data.zip"); if (!System.IO.Directory.Exists(path + "\\zip\\")) System.IO.Directory.CreateDirectory(path + "\\zip\\"); List folders = new List(); folders.Add(path + "\\Excels\\"); string timeTemp = DateTime.Now.ToString("yyyyMM"); ZipManyFilesOrDictorys(folders, path + "\\zip\\" + timeTemp + ".zip", ""); return "" + timeTemp + ".zip"; } catch (Exception e) { return e.Message; throw; } } public static string ListToExcel(List list, string path, string sendUser, string sendCom, out string filename,string mainduiname,string useduiname, string ISCHAOQI = "0") { if (list.Count <= 0) { filename = ""; return ""; } String custName = list[0].KeHuMingCheng; String duino = list[0].DuiNo; IWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("1"); #region 格式 ICellStyle styleNormal = hssfworkbook.CreateCellStyle(); styleNormal.BorderBottom = BorderStyle.Thin; styleNormal.BorderLeft = BorderStyle.Thin; styleNormal.BorderRight = BorderStyle.Thin; styleNormal.BorderTop = BorderStyle.Thin; ICellStyle styleNum = hssfworkbook.CreateCellStyle(); IDataFormat dataformat = hssfworkbook.CreateDataFormat(); styleNum.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); styleNum.BorderBottom = BorderStyle.Thin; styleNum.BorderLeft = BorderStyle.Thin; styleNum.BorderRight = BorderStyle.Thin; styleNum.BorderTop = BorderStyle.Thin; ICellStyle styleHeji = hssfworkbook.CreateCellStyle(); styleHeji.BorderBottom = BorderStyle.Thin; styleHeji.BorderLeft = BorderStyle.Thin; styleHeji.BorderRight = BorderStyle.Thin; styleHeji.BorderTop = BorderStyle.Thin; styleHeji.Alignment = HorizontalAlignment.Center; #endregion #region 标题 IRow row0 = sheet.CreateRow(0); ICell cell0 = row0.CreateCell(0); cell0.SetCellValue(sendCom); ICellStyle style0 = hssfworkbook.CreateCellStyle(); style0.Alignment = HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontName = "宋体"; font.FontHeightInPoints = 18; font.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font); cell0.CellStyle = style0; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 11)); #endregion #region 日期 IRow row1 = sheet.CreateRow(1); ICell cel1 = row1.CreateCell(0); ICellStyle style1 = hssfworkbook.CreateCellStyle(); style1.Alignment = HorizontalAlignment.Center; IFont font2 = hssfworkbook.CreateFont(); font2.FontName = "宋体"; font2.FontHeightInPoints = 14; font2.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font2); cel1.CellStyle = style1; sheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 10)); if (useduiname=="1") cel1.SetCellValue(mainduiname); else cel1.SetCellValue("(" + DateTime.Now.ToString("yyyyMM") + ")费用确认单"); #endregion if (ISCHAOQI == "1"|| ISCHAOQI == "2") { IRow row3 = sheet.CreateRow(2); ICell cel3 = row3.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, 11)); cel3.SetCellValue("尊敬的客户:"); #region 对账客户 IRow row2 = sheet.CreateRow(3); ICell cel2 = row2.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(3, 3, 0, 11)); cel2.SetCellValue("贵司在我司订舱的如下货物即将产生滞纳金,请合理安排付款,避免超期。如已付款,请忽略。谢谢合作!"); #endregion } else { #region 对账客户 string email = ""; string qq = ""; string phone = GetPhoneWithUserId(out email, out qq); _email = email; IRow row2 = sheet.CreateRow(2); ICell cel2 = row2.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, 10)); cel2.SetCellValue("对账联系人:" + sendUser + " 联系电话:" + phone + " E-Mail:" + email + " QQ:" + qq + " 对账编号:" + duino); #endregion #region 对账联系人 IRow row3 = sheet.CreateRow(3); ICell cel3 = row3.CreateCell(0); row3.Height = 0; #endregion } #region 表头 IRow row4 = sheet.CreateRow(4); ICell head0 = row4.CreateCell(0); head0.CellStyle = styleNormal; head0.SetCellValue("对账抬头"); ICell head1 = row4.CreateCell(1); head1.CellStyle = styleNormal; head1.SetCellValue("开船日"); ICell head2 = row4.CreateCell(2); head2.CellStyle = styleNormal; head2.SetCellValue("船名"); ICell head3 = row4.CreateCell(3); head3.CellStyle = styleNormal; head3.SetCellValue("航次"); ICell head4 = row4.CreateCell(4); head4.CellStyle = styleNormal; head4.SetCellValue("目的港"); ICell head5 = row4.CreateCell(5); head5.CellStyle = styleNormal; head5.SetCellValue("MB/L No"); ICell head6 = row4.CreateCell(6); head6.CellStyle = styleNormal; head6.SetCellValue("操作"); ICell head7 = row4.CreateCell(7); head7.CellStyle = styleNormal; head7.SetCellValue("销售"); ICell head8 = row4.CreateCell(8); head8.CellStyle = styleNormal; head8.SetCellValue("应收RMB"); ICell head9 = row4.CreateCell(9); head9.CellStyle = styleNormal; head9.SetCellValue("应收USD"); ICell head10 = row4.CreateCell(10); head10.CellStyle = styleNormal; head10.SetCellValue("应付RMB"); ICell head11 = row4.CreateCell(11); head11.CellStyle = styleNormal; head11.SetCellValue("应付USD"); #endregion #region 明细 int rowindex = 5; double sumRmb = 0; double sumUsd = 0; double sumFRmb = 0; double sumFUsd = 0; foreach (var item in list) { IRow r = sheet.CreateRow(rowindex); ICell c0 = r.CreateCell(0); c0.CellStyle = styleNormal; c0.SetCellValue(item.KeHuMingCheng); ICell c1 = r.CreateCell(1); c1.CellStyle = styleNormal; c1.SetCellValue(item.KaiChuanRi); ICell c2 = r.CreateCell(2); c2.CellStyle = styleNormal; c2.SetCellValue(item.ChuanMing); ICell c3 = r.CreateCell(3); c3.CellStyle = styleNormal; c3.SetCellValue(item.HangCi); ICell c4 = r.CreateCell(4); c4.CellStyle = styleNormal; c4.SetCellValue(item.MuDiGang); ICell c5 = r.CreateCell(5); c5.CellStyle = styleNormal; c5.SetCellValue(item.MBLNO); ICell c6 = r.CreateCell(6); c6.CellStyle = styleNormal; c6.SetCellValue(item.OP); ICell c7 = r.CreateCell(7); c7.CellStyle = styleNormal; c7.SetCellValue(item.SALE); ICell c8 = r.CreateCell(8); c8.CellStyle = styleNum; ICell c9 = r.CreateCell(9); c9.CellStyle = styleNum; ICell c10 = r.CreateCell(10); c10.CellStyle = styleNum; ICell c11 = r.CreateCell(11); c11.CellStyle = styleNum; if (item.RMB == "" || item.RMB == null) { c8.SetCellValue(0); sumRmb += 0; } else { c8.SetCellType(CellType.Numeric); c8.SetCellValue(double.Parse(item.RMB)); sumRmb += double.Parse(item.RMB); } if (item.USD == "" || item.USD == null) { c9.SetCellType(CellType.Numeric); c9.SetCellValue(0); sumUsd += 0; } else { c9.SetCellValue(double.Parse(item.USD)); sumUsd += double.Parse(item.USD); } //应付 if (item.FRMB == "" || item.FRMB == null) { c10.SetCellValue(0); sumFRmb += 0; } else { c10.SetCellType(CellType.Numeric); c10.SetCellValue(double.Parse(item.FRMB)); sumFRmb += double.Parse(item.FRMB); } if (item.FUSD == "" || item.FUSD == null) { c11.SetCellType(CellType.Numeric); c11.SetCellValue(0); sumFUsd += 0; } else { c11.SetCellValue(double.Parse(item.FUSD)); sumFUsd += double.Parse(item.FUSD); } rowindex++; } IRow rtotal = sheet.CreateRow(rowindex); ICell ct0 = rtotal.CreateCell(0); ct0.CellStyle = styleHeji; ct0.SetCellValue("合计"); for (int i = 1; i < 9; i++) { ICell ct1 = rtotal.CreateCell(i); ct1.CellStyle = styleNormal; ct1.SetCellValue(""); } ICell ctrmb = rtotal.CreateCell(8); //ctrmb.SetCellType(CellType.Numeric); ctrmb.CellStyle = styleNum; ctrmb.SetCellValue(sumRmb); ICell ctusd = rtotal.CreateCell(9); ctusd.CellStyle = styleNum; ctusd.SetCellValue(sumUsd); ICell ctfrmb = rtotal.CreateCell(10); ctfrmb.CellStyle = styleNum; ctfrmb.SetCellValue(sumFRmb); ICell ctfusd = rtotal.CreateCell(11); ctfusd.CellStyle = styleNum; ctfusd.SetCellValue(sumFUsd); //列宽 sheet.SetColumnWidth(0, 32 * 256); sheet.SetColumnWidth(1, 20 * 256); sheet.SetColumnWidth(2, 20 * 256); sheet.SetColumnWidth(3, 28 * 256); sheet.SetColumnWidth(4, 20 * 256); sheet.SetColumnWidth(5, 25 * 256); sheet.SetColumnWidth(6, 20 * 256); sheet.SetColumnWidth(7, 20 * 256); sheet.SetColumnWidth(8, 20 * 256); sheet.SetColumnWidth(9, 20 * 256); sheet.SetColumnWidth(10, 20 * 256); sheet.SetColumnWidth(11, 20 * 256); sheet.AddMergedRegion(new CellRangeAddress(rowindex, rowindex, 0, 7)); #endregion if (ISCHAOQI == "1" || ISCHAOQI == "2") { IRow rowsum = sheet.CreateRow(rowindex + 1); ICell celsum = rowsum.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(rowindex + 1, rowindex + 1, 0, 11)); celsum.SetCellValue("滞纳金收取标准:(人民币欠费+美金欠费X实时汇率)X5‰X超期天数"); } if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); string fileName = "[" + custName + "]" + mainduiname+"_"+ DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; using (FileStream file = new FileStream(path + "\\" + fileName, FileMode.Create)) { hssfworkbook.Write(file);  //创建test.xls文件。 file.Close(); } filename = fileName; return path + "\\" + fileName; } public static string ListToExcelNoDay(List list, string path, string sendUser, string sendCom, out string filename, string mainduiname, string useduiname, decimal EXCHANGERATE = 0,string ISCHAOQI="0") { if (list.Count <= 0) { filename = ""; return ""; } String custName = list[0].KeHuMingCheng; String duino = list[0].DuiNo; IWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("1"); #region 格式 ICellStyle styleNormal = hssfworkbook.CreateCellStyle(); styleNormal.BorderBottom = BorderStyle.Thin; styleNormal.BorderLeft = BorderStyle.Thin; styleNormal.BorderRight = BorderStyle.Thin; styleNormal.BorderTop = BorderStyle.Thin; ICellStyle styleNum = hssfworkbook.CreateCellStyle(); IDataFormat dataformat = hssfworkbook.CreateDataFormat(); styleNum.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); styleNum.BorderBottom = BorderStyle.Thin; styleNum.BorderLeft = BorderStyle.Thin; styleNum.BorderRight = BorderStyle.Thin; styleNum.BorderTop = BorderStyle.Thin; ICellStyle styleHeji = hssfworkbook.CreateCellStyle(); styleHeji.BorderBottom = BorderStyle.Thin; styleHeji.BorderLeft = BorderStyle.Thin; styleHeji.BorderRight = BorderStyle.Thin; styleHeji.BorderTop = BorderStyle.Thin; styleHeji.Alignment = HorizontalAlignment.Center; #endregion #region 标题 IRow row0 = sheet.CreateRow(0); ICell cell0 = row0.CreateCell(0); cell0.SetCellValue(sendCom); ICellStyle style0 = hssfworkbook.CreateCellStyle(); style0.Alignment = HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontName = "宋体"; font.FontHeightInPoints = 18; font.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font); cell0.CellStyle = style0; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 11)); #endregion #region 日期 IRow row1 = sheet.CreateRow(1); ICell cel1 = row1.CreateCell(0); ICellStyle style1 = hssfworkbook.CreateCellStyle(); style1.Alignment = HorizontalAlignment.Center; IFont font2 = hssfworkbook.CreateFont(); font2.FontName = "宋体"; font2.FontHeightInPoints = 14; font2.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font2); cel1.CellStyle = style1; sheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 13)); if (useduiname == "1") cel1.SetCellValue(mainduiname); else cel1.SetCellValue("(" + DateTime.Now.ToString("yyyyMM") + ")滞纳金收费通知"); #endregion IRow row3 = sheet.CreateRow(2); ICell cel3 = row3.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, 13)); cel3.SetCellValue("尊敬的客户:"); double sumNOAMOUNT = 0; if (ISCHAOQI == "1") { foreach (var item in list) { if (item.NOAMOUNT == "" || item.NOAMOUNT == null) { sumNOAMOUNT += 0; } else { sumNOAMOUNT += double.Parse(item.NOAMOUNT); } } } #region 对账客户 string email = ""; string qq = ""; string phone = GetPhoneWithUserId(out email, out qq); _email = email; IRow row2 = sheet.CreateRow(3); ICell cel2 = row2.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(3, 3, 0, 13)); if (ISCHAOQI!="1") cel2.SetCellValue("贵司在我司订舱的如下货物即将产生滞纳金,请合理安排付款,避免超期。如已付款,请忽略。谢谢合作!"); else cel2.SetCellValue("截止到今天为止,贵司在我司订舱的如下货物已产生累计:" + Math.Round(sumNOAMOUNT, 2, MidpointRounding.AwayFromZero).ToString() + "元滞纳金。请尽快安排付款买单,如已付款,请忽略。谢谢合作!"); #endregion #region 对账联系人 #endregion #region 表头 IRow row4 = sheet.CreateRow(4); ICell head0 = row4.CreateCell(0); head0.CellStyle = styleNormal; head0.SetCellValue("对账抬头"); ICell head1 = row4.CreateCell(1); head1.CellStyle = styleNormal; head1.SetCellValue("开船日"); ICell head2 = row4.CreateCell(2); head2.CellStyle = styleNormal; head2.SetCellValue("船名"); ICell head3 = row4.CreateCell(3); head3.CellStyle = styleNormal; head3.SetCellValue("航次"); ICell head4 = row4.CreateCell(4); head4.CellStyle = styleNormal; head4.SetCellValue("目的港"); ICell head5 = row4.CreateCell(5); head5.CellStyle = styleNormal; head5.SetCellValue("MB/L No"); ICell head6 = row4.CreateCell(6); head6.CellStyle = styleNormal; head6.SetCellValue("操作"); ICell head7 = row4.CreateCell(7); head7.CellStyle = styleNormal; head7.SetCellValue("销售"); ICell head8 = row4.CreateCell(8); head8.CellStyle = styleNormal; head8.SetCellValue("应收RMB"); ICell head9 = row4.CreateCell(9); head9.CellStyle = styleNormal; head9.SetCellValue("应收USD"); ICell head10 = row4.CreateCell(10); head10.CellStyle = styleNormal; head10.SetCellValue("应付RMB"); ICell head11 = row4.CreateCell(11); head11.CellStyle = styleNormal; head11.SetCellValue("应付USD"); ICell head12 = row4.CreateCell(12); head12.CellStyle = styleNormal; head12.SetCellValue("超期天数"); ICell head13 = row4.CreateCell(13); head13.CellStyle = styleNormal; head13.SetCellValue("滞期费"); #endregion #region 明细 int rowindex = 5; double sumRmb = 0; double sumUsd = 0; double sumFRmb = 0; double sumFUsd = 0; foreach (var item in list) { IRow r = sheet.CreateRow(rowindex); ICell c0 = r.CreateCell(0); c0.CellStyle = styleNormal; c0.SetCellValue(item.KeHuMingCheng); ICell c1 = r.CreateCell(1); c1.CellStyle = styleNormal; c1.SetCellValue(item.KaiChuanRi); ICell c2 = r.CreateCell(2); c2.CellStyle = styleNormal; c2.SetCellValue(item.ChuanMing); ICell c3 = r.CreateCell(3); c3.CellStyle = styleNormal; c3.SetCellValue(item.HangCi); ICell c4 = r.CreateCell(4); c4.CellStyle = styleNormal; c4.SetCellValue(item.MuDiGang); ICell c5 = r.CreateCell(5); c5.CellStyle = styleNormal; c5.SetCellValue(item.MBLNO); ICell c6 = r.CreateCell(6); c6.CellStyle = styleNormal; c6.SetCellValue(item.OP); ICell c7 = r.CreateCell(7); c7.CellStyle = styleNormal; c7.SetCellValue(item.SALE); ICell c8 = r.CreateCell(8); c8.CellStyle = styleNum; ICell c9 = r.CreateCell(9); c9.CellStyle = styleNum; ICell c10 = r.CreateCell(10); c10.CellStyle = styleNum; ICell c11 = r.CreateCell(11); c11.CellStyle = styleNum; ICell c12 = r.CreateCell(12); c12.CellStyle = styleNormal; c12.SetCellValue(item.NODAY); ICell c13 = r.CreateCell(13); c13.CellStyle = styleNum; if (item.RMB == "" || item.RMB == null) { c8.SetCellValue(0); sumRmb += 0; } else { c8.SetCellType(CellType.Numeric); c8.SetCellValue(double.Parse(item.RMB)); sumRmb += double.Parse(item.RMB); } if (item.USD == "" || item.USD == null) { c9.SetCellType(CellType.Numeric); c9.SetCellValue(0); sumUsd += 0; } else { c9.SetCellValue(double.Parse(item.USD)); sumUsd += double.Parse(item.USD); } //应付 if (item.FRMB == "" || item.FRMB == null) { c10.SetCellValue(0); sumFRmb += 0; } else { c10.SetCellType(CellType.Numeric); c10.SetCellValue(double.Parse(item.FRMB)); sumFRmb += double.Parse(item.FRMB); } if (item.FUSD == "" || item.FUSD == null) { c11.SetCellType(CellType.Numeric); c11.SetCellValue(0); sumFUsd += 0; } else { c11.SetCellValue(double.Parse(item.FUSD)); sumFUsd += double.Parse(item.FUSD); } if (item.NOAMOUNT == "" || item.NOAMOUNT == null|| ISCHAOQI != "1") { c13.SetCellType(CellType.Numeric); c13.SetCellValue(0); } else { c13.SetCellValue(double.Parse(item.NOAMOUNT)); } rowindex++; } IRow rtotal = sheet.CreateRow(rowindex); ICell ct0 = rtotal.CreateCell(0); ct0.CellStyle = styleHeji; ct0.SetCellValue("合计"); for (int i = 1; i < 9; i++) { ICell ct1 = rtotal.CreateCell(i); ct1.CellStyle = styleNormal; ct1.SetCellValue(""); } ICell ctrmb = rtotal.CreateCell(8); //ctrmb.SetCellType(CellType.Numeric); ctrmb.CellStyle = styleNum; ctrmb.SetCellValue(sumRmb); ICell ctusd = rtotal.CreateCell(9); ctusd.CellStyle = styleNum; ctusd.SetCellValue(sumUsd); ICell ctfrmb = rtotal.CreateCell(10); ctfrmb.CellStyle = styleNum; ctfrmb.SetCellValue(sumFRmb); ICell ctfusd = rtotal.CreateCell(11); ctfusd.CellStyle = styleNum; ctfusd.SetCellValue(sumFUsd); ICell ct12 = rtotal.CreateCell(12); ct12.CellStyle = styleNormal; ct12.SetCellValue(""); ICell ctfnoamount= rtotal.CreateCell(13); ctfnoamount.CellStyle = styleNum; ctfnoamount.SetCellValue(sumNOAMOUNT); //列宽 sheet.SetColumnWidth(0, 32 * 256); sheet.SetColumnWidth(1, 20 * 256); sheet.SetColumnWidth(2, 20 * 256); sheet.SetColumnWidth(3, 28 * 256); sheet.SetColumnWidth(4, 20 * 256); sheet.SetColumnWidth(5, 25 * 256); sheet.SetColumnWidth(6, 20 * 256); sheet.SetColumnWidth(7, 20 * 256); sheet.SetColumnWidth(8, 20 * 256); sheet.SetColumnWidth(9, 20 * 256); sheet.SetColumnWidth(10, 20 * 256); sheet.SetColumnWidth(11, 20 * 256); sheet.SetColumnWidth(12, 20 * 256); sheet.SetColumnWidth(13, 20 * 256); sheet.AddMergedRegion(new CellRangeAddress(rowindex, rowindex, 0, 7)); #endregion IRow rowsum = sheet.CreateRow(rowindex+1); ICell celsum = rowsum.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(rowindex + 1, rowindex + 1, 0, 13)); celsum.SetCellValue("滞纳金收取标准:人民币欠费+美金欠费X"+ EXCHANGERATE.ToString() + "X5‰X超期天数"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); string fileName = "[" + custName + "]" + mainduiname + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; using (FileStream file = new FileStream(path + "\\" + fileName, FileMode.Create)) { hssfworkbook.Write(file);  //创建test.xls文件。 file.Close(); } filename = fileName; return path + "\\" + fileName; } public static string ListToExcelNoOpSale(List list, string path, string sendUser, string sendCom, out string filename, string mainduiname, string useduiname) { if (list.Count <= 0) { filename = ""; return ""; } String custName = list[0].KeHuMingCheng; String duino = list[0].DuiNo; IWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("1"); #region 格式 ICellStyle styleNormal = hssfworkbook.CreateCellStyle(); styleNormal.BorderBottom = BorderStyle.Thin; styleNormal.BorderLeft = BorderStyle.Thin; styleNormal.BorderRight = BorderStyle.Thin; styleNormal.BorderTop = BorderStyle.Thin; ICellStyle styleNum = hssfworkbook.CreateCellStyle(); IDataFormat dataformat = hssfworkbook.CreateDataFormat(); styleNum.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); styleNum.BorderBottom = BorderStyle.Thin; styleNum.BorderLeft = BorderStyle.Thin; styleNum.BorderRight = BorderStyle.Thin; styleNum.BorderTop = BorderStyle.Thin; ICellStyle styleHeji = hssfworkbook.CreateCellStyle(); styleHeji.BorderBottom = BorderStyle.Thin; styleHeji.BorderLeft = BorderStyle.Thin; styleHeji.BorderRight = BorderStyle.Thin; styleHeji.BorderTop = BorderStyle.Thin; styleHeji.Alignment = HorizontalAlignment.Center; #endregion #region 标题 IRow row0 = sheet.CreateRow(0); ICell cell0 = row0.CreateCell(0); cell0.SetCellValue(sendCom); ICellStyle style0 = hssfworkbook.CreateCellStyle(); style0.Alignment = HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontName = "宋体"; font.FontHeightInPoints = 18; font.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font); cell0.CellStyle = style0; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 11)); #endregion #region 日期 IRow row1 = sheet.CreateRow(1); ICell cel1 = row1.CreateCell(0); ICellStyle style1 = hssfworkbook.CreateCellStyle(); style1.Alignment = HorizontalAlignment.Center; IFont font2 = hssfworkbook.CreateFont(); font2.FontName = "宋体"; font2.FontHeightInPoints = 14; font2.Boldweight = (short)FontBoldWeight.Bold; style0.SetFont(font2); cel1.CellStyle = style1; sheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 10)); if (useduiname == "1") cel1.SetCellValue(mainduiname); else cel1.SetCellValue("(" + DateTime.Now.ToString("yyyyMM") + ")费用确认单"); #endregion #region 对账客户 string email = ""; string qq = ""; string phone = GetPhoneWithUserId(out email, out qq); _email = email; IRow row2 = sheet.CreateRow(2); ICell cel2 = row2.CreateCell(0); sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, 10)); cel2.SetCellValue("对账联系人:" + sendUser + " 联系电话:" + phone + " E-Mail:" + email + " QQ:" + qq + " 对账编号:" + duino); #endregion #region 对账联系人 IRow row3 = sheet.CreateRow(3); ICell cel3 = row3.CreateCell(0); row3.Height = 0; #endregion #region 表头 IRow row4 = sheet.CreateRow(4); ICell head0 = row4.CreateCell(0); head0.CellStyle = styleNormal; head0.SetCellValue("对账抬头"); ICell head1 = row4.CreateCell(1); head1.CellStyle = styleNormal; head1.SetCellValue("开船日"); ICell head2 = row4.CreateCell(2); head2.CellStyle = styleNormal; head2.SetCellValue("船名"); ICell head3 = row4.CreateCell(3); head3.CellStyle = styleNormal; head3.SetCellValue("航次"); ICell head4 = row4.CreateCell(4); head4.CellStyle = styleNormal; head4.SetCellValue("目的港"); ICell head5 = row4.CreateCell(5); head5.CellStyle = styleNormal; head5.SetCellValue("MB/L No"); ICell head8 = row4.CreateCell(6); head8.CellStyle = styleNormal; head8.SetCellValue("应收RMB"); ICell head9 = row4.CreateCell(7); head9.CellStyle = styleNormal; head9.SetCellValue("应收USD"); ICell head10 = row4.CreateCell(8); head10.CellStyle = styleNormal; head10.SetCellValue("应付RMB"); ICell head11 = row4.CreateCell(9); head11.CellStyle = styleNormal; head11.SetCellValue("应付USD"); #endregion #region 明细 int rowindex = 5; double sumRmb = 0; double sumUsd = 0; double sumFRmb = 0; double sumFUsd = 0; foreach (var item in list) { IRow r = sheet.CreateRow(rowindex); ICell c0 = r.CreateCell(0); c0.CellStyle = styleNormal; c0.SetCellValue(item.KeHuMingCheng); ICell c1 = r.CreateCell(1); c1.CellStyle = styleNormal; c1.SetCellValue(item.KaiChuanRi); ICell c2 = r.CreateCell(2); c2.CellStyle = styleNormal; c2.SetCellValue(item.ChuanMing); ICell c3 = r.CreateCell(3); c3.CellStyle = styleNormal; c3.SetCellValue(item.HangCi); ICell c4 = r.CreateCell(4); c4.CellStyle = styleNormal; c4.SetCellValue(item.MuDiGang); ICell c5 = r.CreateCell(5); c5.CellStyle = styleNormal; c5.SetCellValue(item.MBLNO); //ICell c6 = r.CreateCell(6); //c6.CellStyle = styleNormal; //c6.SetCellValue(item.OP); //ICell c7 = r.CreateCell(7); //c7.CellStyle = styleNormal; //c7.SetCellValue(item.SALE); ICell c8 = r.CreateCell(6); c8.CellStyle = styleNum; ICell c9 = r.CreateCell(7); c9.CellStyle = styleNum; ICell c10 = r.CreateCell(8); c10.CellStyle = styleNum; ICell c11 = r.CreateCell(9); c11.CellStyle = styleNum; if (item.RMB == "" || item.RMB == null) { c8.SetCellValue(0); sumRmb += 0; } else { c8.SetCellType(CellType.Numeric); c8.SetCellValue(double.Parse(item.RMB)); sumRmb += double.Parse(item.RMB); } if (item.USD == "" || item.USD == null) { c9.SetCellType(CellType.Numeric); c9.SetCellValue(0); sumUsd += 0; } else { c9.SetCellValue(double.Parse(item.USD)); sumUsd += double.Parse(item.USD); } //应付 if (item.FRMB == "" || item.FRMB == null) { c10.SetCellValue(0); sumFRmb += 0; } else { c10.SetCellType(CellType.Numeric); c10.SetCellValue(double.Parse(item.FRMB)); sumFRmb += double.Parse(item.FRMB); } if (item.FUSD == "" || item.FUSD == null) { c11.SetCellType(CellType.Numeric); c11.SetCellValue(0); sumFUsd += 0; } else { c11.SetCellValue(double.Parse(item.FUSD)); sumFUsd += double.Parse(item.FUSD); } rowindex++; } IRow rtotal = sheet.CreateRow(rowindex); ICell ct0 = rtotal.CreateCell(0); ct0.CellStyle = styleHeji; ct0.SetCellValue("合计"); for (int i = 1; i < 7; i++) { ICell ct1 = rtotal.CreateCell(i); ct1.CellStyle = styleNormal; ct1.SetCellValue(""); } ICell ctrmb = rtotal.CreateCell(6); //ctrmb.SetCellType(CellType.Numeric); ctrmb.CellStyle = styleNum; ctrmb.SetCellValue(sumRmb); ICell ctusd = rtotal.CreateCell(7); ctusd.CellStyle = styleNum; ctusd.SetCellValue(sumUsd); ICell ctfrmb = rtotal.CreateCell(8); ctfrmb.CellStyle = styleNum; ctfrmb.SetCellValue(sumFRmb); ICell ctfusd = rtotal.CreateCell(9); ctfusd.CellStyle = styleNum; ctfusd.SetCellValue(sumFUsd); //列宽 sheet.SetColumnWidth(0, 32 * 256); sheet.SetColumnWidth(1, 20 * 256); sheet.SetColumnWidth(2, 20 * 256); sheet.SetColumnWidth(3, 28 * 256); sheet.SetColumnWidth(4, 20 * 256); sheet.SetColumnWidth(5, 25 * 256); //sheet.SetColumnWidth(6, 20 * 256); //sheet.SetColumnWidth(7, 20 * 256); sheet.SetColumnWidth(6, 20 * 256); sheet.SetColumnWidth(7, 20 * 256); sheet.SetColumnWidth(8, 20 * 256); sheet.SetColumnWidth(9, 20 * 256); sheet.AddMergedRegion(new CellRangeAddress(rowindex, rowindex, 0, 5)); #endregion if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); string fileName = "[" + custName + "]" + mainduiname + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; using (FileStream file = new FileStream(path + "\\" + fileName, FileMode.Create)) { hssfworkbook.Write(file);  //创建test.xls文件。 file.Close(); } filename = fileName; return path + "\\" + fileName; } private static DBResult SendMailWithExcelFile(string title, string context, string excelPath, string custMailAddress,string ccmailaddr, string comname, string toname,DSWeb.SoftMng.Model.EmailConfig model,string username,string cc) { var result = new DBResult(); // SendEmail se = new SendEmail("dongshengsoft@dongshengsoft.com", "admin@dongshengsoft.com", "", "", title, context, false); // se.SetSmtp("admin@dongshengsoft.com", "ds!@#)(*", "smtpcom.263xmail.com", 25, false, //System.Net.Mail.MailPriority.Normal); if (custMailAddress=="") { result.Success = false; result.Message = "客户邮箱不能为空!"; return result; } try { //var ccList = new List(); //ccList.Add("*****@qq.com"); var recipients = new List(); var ccList = new List(); string[] emailList = custMailAddress.Split(';'); foreach (var m in emailList) { if (m.Trim()!="") recipients.Add(m); } var opmail = ""; if (cc == "1") { string[] ccemailList = ccmailaddr.Split(';'); var i = 0; foreach (var m in ccemailList) { if (m.Trim() != "") ccList.Add(m); if (i == 0) opmail = m; i = i + 1; } } if (opmail == "") opmail = model.EmailAccount; var mailBodyEntity = new MailBodyEntity() { Body = context, Cc = ccList, //MailBodyType = "html", MailFiles = new List() { new MailFile { MailFilePath = excelPath, MailFileSubType = "xls", MailFileType = "xls" } }, Recipients = recipients, Sender = opmail, SenderAddress = opmail, Subject = title, }; var sendServerConfiguration = new SendServerConfigurationEntity() { SenderPassword = model.EmailPass, SmtpPort = Convert.ToInt32(model.Port), IsSsl = true, MailEncoding = "utf-8", SenderAccount = model.EmailAccount, SmtpHost = model.ServerAddr, }; var Mailresult = MailHelper.SendMail(mailBodyEntity, sendServerConfiguration); if (Mailresult.ResultStatus == true) { var filename = Path.GetFileName(excelPath); var head = new OpMailLog(); head.BSNO = ""; head.BLTYPE = "自动对账"; head.RECEIVER = custMailAddress; head.SUBJECT = title; head.DESCRIPTION = context; head.ATTACHMENT = "../../ AutoDuiFiles / Excels" + filename; head.SENDER = username; head.SENDTIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); head.DbOperationType = DbOperationType.DbotIns; var modb = new ModelObjectDB(); modb.Save(head); } else { result.Success = Mailresult.ResultStatus; result.Message = Mailresult.ResultInformation; return result; } //ReceiveEmailHelper.ReceiveEmail(); //ReceiveEmailHelper.DownloadBodyParts(); //Console.WriteLine("成功!"); //Console.ReadLine(); } catch (Exception ex) { result.Success = false; result.Message = ex.Message; return result; } result.Success = true; result.Message ="发送成功!"; return result; //SendEmail se = new SendEmail(custMailAddress, model.EmailAccount, "", "", title, context, false); //// SendEmail se = new SendEmail("dev001@dongshengsoft.com", "admin@dongshengsoft.com", "", "", mailtopic, mailbody, false); //se.Attachments(excelPath); //try //{ // se.SetSmtp(model.EmailAccount, model.EmailPass, model.ServerAddr, Convert.ToInt32(model.Port), true, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法 // var filename = Path.GetFileName(excelPath); // var head = new OpMailLog(); // head.BSNO = ""; // head.BLTYPE = "自动对账"; // head.RECEIVER = custMailAddress; // head.SUBJECT = title; // head.DESCRIPTION = context; // head.ATTACHMENT = "../../ AutoDuiFiles / Excels" + filename; // head.SENDER = username; // head.SENDTIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // head.DbOperationType = DbOperationType.DbotIns; // var modb = new ModelObjectDB(); // modb.Save(head); //} //catch (Exception e) //{ // se.SetSmtp(model.EmailAccount, model.EmailPass, model.ServerAddr, Convert.ToInt32(model.Port), false, System.Net.Mail.MailPriority.Normal); //必须在所有参数设置完后调用此方法 // // //} //var useremail = _email; //if (useremail.Trim() == "") useremail = "admin@dongshengsoft.com"; //MailAddress mafrom = new MailAddress(useremail, comname, Encoding.GetEncoding(936)); //MailAddress mato = new MailAddress(custMailAddress, toname, Encoding.GetEncoding(936)); //using (var smtp = new SmtpClient()) ////TO: //using (var mail = new MailMessage(mafrom, mato)) //{ // //附件 // var attach = new Attachment(excelPath, MediaTypeNames.Application.Octet); // //设置ContentId // mail.Attachments.Add(attach); // //标题和内容,注意设置编码,因为默认编码是ASCII // mail.Subject = title; // mail.SubjectEncoding = Encoding.UTF8; // //HTML内容 // mail.Body = context; // mail.BodyEncoding = Encoding.UTF8; // //指示改电子邮件内容是HTML格式 // mail.IsBodyHtml = true; // //SMTP设置(根据邮箱类型设置,这里是Live Mail的SMTP服务器地址) // smtp.Host = model.ServerAddr;// "smtpcom.263xmail.com";//服务器地址 // smtp.Port = Convert.ToInt32(model.Port);// 465;//端口 // smtp.EnableSsl =Convert.ToBoolean(model.SSL);// false;//SSL // smtp.UseDefaultCredentials = false; // smtp.Credentials = new NetworkCredential(model.EmailAccount, model.EmailPass);//new NetworkCredential("admin@dongshengsoft.com", "ds!@#)(*");//账号密码 // smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // //发送 // smtp.Send(mail); // var filename = Path.GetFileName(excelPath); // var head = new OpMailLog(); // head.BSNO = ""; // head.BLTYPE ="自动对账"; // head.RECEIVER = custMailAddress; // head.SUBJECT = title; // head.DESCRIPTION = context; // head.ATTACHMENT = "../../ AutoDuiFiles / Excels" + filename; // head.SENDER = username; // head.SENDTIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // head.DbOperationType = DbOperationType.DbotIns; // var modb = new ModelObjectDB(); // modb.Save(head); //} } private static string GetUserNameWithUserId(string userid) { string sql = "select showname from [user] where gid = '" + userid + "' "; Database db = DatabaseFactory.CreateDatabase(); return db.ExecuteScalar(CommandType.Text, sql).ToString(); } private static string GetComNameWithComId(string comid) { string sql = "select fullname from company where gid = '" + comid + "' "; Database db = DatabaseFactory.CreateDatabase(); return db.ExecuteScalar(CommandType.Text, sql).ToString(); } private static string GetPhoneWithUserId(out string email, out string qq) { string sql = "select officephone,EMAIL1,QQ from user_baseinfo where userid = '" + _UserId + "' "; Database db = DatabaseFactory.CreateDatabase(); string phone = ""; email = ""; qq = ""; using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql)) { while (reader.Read()) { phone = reader["officephone"].ToString(); email = reader["EMAIL1"].ToString(); qq = reader["QQ"].ToString(); } reader.Close(); } return phone; } private static void CreateZipFile(string filesPath, string zipFilePath) { if (!Directory.Exists(filesPath)) { Console.WriteLine("Cannot find directory '{0}'", filesPath); return; } try { string[] filenames = Directory.GetFiles(filesPath); using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); // 压缩级别 0-9 //s.Password = "123"; //Zip压缩文件密码 byte[] buffer = new byte[4096]; //缓冲区大小 foreach (string file in filenames) { ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } s.Finish(); s.Close(); } } catch (Exception ex) { Console.WriteLine("Exception during processing {0}", ex); } } /// /// 压缩多个目录或文件 /// /// 待压缩的文件夹或者文件,全路径格式,是一个集合 /// 压缩后的文件名,全路径格式 /// 压宿密码 /// public static bool ZipManyFilesOrDictorys(IEnumerable folderOrFileList, string zipedFile, string password) { bool res = true; using (var s = new ZipOutputStream(File.Create(zipedFile))) { s.SetLevel(6); if (!string.IsNullOrEmpty(password)) { s.Password = password; } foreach (string fileOrDir in folderOrFileList) { //是文件夹 if (Directory.Exists(fileOrDir)) { res = ZipFileDictory(fileOrDir, s, ""); } else { //文件 res = ZipFileWithStream(fileOrDir, s); } } s.Finish(); s.Close(); return res; } } /// /// 递归压缩文件夹方法 /// /// /// /// private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName) { bool res = true; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 var filenames = Directory.GetFiles(folderToZip); foreach (string file in filenames) { //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } catch { res = false; } finally { if (fs != null) { fs.Close(); } if (entry != null) { } GC.Collect(); GC.Collect(1); } var folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip)))) { return false; } } return res; } /// /// 带压缩流压缩单个文件 /// /// 要进行压缩的文件名 /// /// private static bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream) { //如果文件没有找到,则报错 if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } //FileStream fs = null; FileStream zipFile = null; ZipEntry zipEntry = null; bool res = true; try { zipFile = File.OpenRead(fileToZip); byte[] buffer = new byte[zipFile.Length]; zipFile.Read(buffer, 0, buffer.Length); zipFile.Close(); zipEntry = new ZipEntry(Path.GetFileName(fileToZip)); zipStream.PutNextEntry(zipEntry); zipStream.Write(buffer, 0, buffer.Length); } catch { res = false; } finally { if (zipEntry != null) { } if (zipFile != null) { zipFile.Close(); } GC.Collect(); GC.Collect(1); } return res; } public static bool CreateAndUpdateDui(string condition, string dMainId, string comid, string usershowname) { try { //获取ch_fee.id 集合 var strSql = new StringBuilder(); strSql.Append(@"SELECT C.CUSTOMERNAME, C.GID, VB.BSNO FROM ch_fee C LEFT JOIN v_op_bill VB on VB.BSNO = C.BSNO WHERE 1=1 and C.CUSTOMERNAME <>'' "); if (condition != "") { strSql.Append(condition); } strSql.Append("order by C.CUSTOMERNAME"); Database db = DatabaseFactory.CreateDatabase(); List listc = new List(); using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString())) { while (reader.Read()) { MsChFeeYsAutoDuiCreateModel m = new MsChFeeYsAutoDuiCreateModel(); m.FeeGid = reader["GID"].ToString(); m.CustomerName = reader["CUSTOMERNAME"].ToString(); m.BSNO = reader["BSNO"].ToString(); listc.Add(m); } } //每一个客户生成一个对账编号并更新ch_fee.isdebit,ch_fee.debitno string custtemp = ""; string DuiNo = ""; List listDbtFee = new List(); List listdui = new List(); int i = 0; foreach (var item in listc) { if (item.CustomerName == custtemp) { MsChFeeYsAutoDuiDebitNoAndFeeGid df = new MsChFeeYsAutoDuiDebitNoAndFeeGid(); df.DebitNo = DuiNo; df.FeeGid = item.FeeGid; listDbtFee.Add(df); MsChFeeYsAutoDuiChDui md = new MsChFeeYsAutoDuiChDui(); md.CUSTNAME = item.CustomerName; md.DUIDATE = DateTime.Now.ToString("yyyy-MM-dd"); md.DuiNo = DuiNo; md.duiType = "1"; md.DUINAME = ""; md.REMARKS = ""; md.OP = usershowname; md.BSNO = item.BSNO; listdui.Add(md); } else { var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='客户对账'", comid); string DUIDATE = DateTime.Now.ToString("yyyy-MM-dd"); if (billnoset.BILLTYPE != "") DuiNo = MsSysBillNoSetDAL.GetBillNo(billnoset, DUIDATE.ToString().Trim(), DUIDATE.ToString().Trim()); else DuiNo = PubSysDAL.GetBillNo("0301"); custtemp = item.CustomerName; MsChFeeYsAutoDuiDebitNoAndFeeGid df = new MsChFeeYsAutoDuiDebitNoAndFeeGid(); df.DebitNo = DuiNo; df.FeeGid = item.FeeGid; listDbtFee.Add(df); MsChFeeYsAutoDuiChDui md = new MsChFeeYsAutoDuiChDui(); md.CUSTNAME = item.CustomerName; md.DUIDATE = DateTime.Now.ToString("yyyy-MM-dd"); md.DuiNo = DuiNo; md.duiType = "1"; md.DUINAME = ""; md.REMARKS = ""; md.OP = usershowname; md.BSNO = item.BSNO; listdui.Add(md); } i++; } UpdateChfeeWithDict(listDbtFee); //每一个客户生成一个对账编号并插入ch_dui InsertChduiWithList(listdui); //将对账编号和dMainId插入ch_dui_main_dui关系表 InsertChduimaindui(listdui,dMainId); //插入数据到ch_dui_bill表 //InsertChDuiBill(listdui); InsertChDuiBill(dMainId); return true; } catch (Exception) { return false; throw; } } private static void UpdateChfeeWithDict(List listDbtFee) { string gids = ""; string debitno = ""; for (int i = 0; i < listDbtFee.Count; i++) { MsChFeeYsAutoDuiDebitNoAndFeeGid df = listDbtFee[i]; if (df.DebitNo == debitno) { gids += "'" + df.FeeGid + "',"; } else { if (debitno != "") { gids = gids.Substring(0, gids.Length - 1); UpdateChfeeWithGidsAndDebitno(gids, debitno); gids = "'" + df.FeeGid + "',"; debitno = df.DebitNo; } else { gids = "'" + df.FeeGid + "',"; debitno = df.DebitNo; } } } //更新最后一组 if ( listDbtFee.Count>0) { gids = gids.Substring(0, gids.Length - 1); UpdateChfeeWithGidsAndDebitno(gids, debitno); } } private static void UpdateChfeeWithGidsAndDebitno(string gids, string debitno) { try { StringBuilder sb = new StringBuilder(); sb.Append("update ch_fee set "); sb.Append("debitno = '" + debitno + "',"); sb.Append("isdebit = 1 "); sb.Append("where gid in (" + gids + ")"); Database db = DatabaseFactory.CreateDatabase(); db.ExecuteNonQuery(CommandType.Text, sb.ToString()); } catch (Exception) { throw; } } private static void InsertChduiWithList(List listdui) { List newList = listdui.Where((x, i) => listdui.FindIndex(z => z.DuiNo == x.DuiNo) == i).ToList(); Database db = DatabaseFactory.CreateDatabase(); StringBuilder insSb = new StringBuilder(); insSb.Append("insert into ch_dui (duino,custname,duidate,op,duiname,duitype) values "); int cnt = 0; foreach (var item in newList) { insSb.Append("("); insSb.Append("'" + item.DuiNo + "',"); insSb.Append("'" + item.CUSTNAME + "',"); insSb.Append("'" + item.DUIDATE + "',"); insSb.Append("'" + item.OP + "',"); insSb.Append("'" + item.DUINAME + "',"); insSb.Append("" + item.duiType + ""); insSb.Append("),"); //超过900行执行一次插入 if (cnt == 900) { string sql = insSb.ToString(); sql = sql.Substring(0, sql.Length - 1); db.ExecuteNonQuery(CommandType.Text, sql); insSb.Clear(); insSb.Append("insert into ch_dui (duino,custname,duidate,op,duiname,duitype) values "); cnt = 0; } cnt++; } if (newList.Count>0) { string sqlIns = insSb.ToString(); sqlIns = sqlIns.Substring(0, sqlIns.Length - 1); db.ExecuteNonQuery(CommandType.Text, sqlIns); } } private static void InsertChduimaindui(List listdui, string mainid) { List newList = listdui.Where((x, i) => listdui.FindIndex(z => z.DuiNo == x.DuiNo) == i).ToList(); Database db = DatabaseFactory.CreateDatabase(); StringBuilder insSb = new StringBuilder(); insSb.Append("insert into ch_dui_main_dui (dMainId,duino) values "); int cnt = 0; foreach (var item in newList) { insSb.Append("("); insSb.Append("'" + mainid + "',"); insSb.Append("'" + item.DuiNo + "'"); insSb.Append("),"); //超过900行执行一次插入 if (cnt == 900) { string sql = insSb.ToString(); sql = sql.Substring(0, sql.Length - 1); db.ExecuteNonQuery(CommandType.Text, sql); insSb.Clear(); insSb.Append("insert into ch_dui_main_dui (dMainId,duino) values "); cnt = 0; } cnt++; } if (newList.Count > 0) { string sqlIns = insSb.ToString(); sqlIns = sqlIns.Substring(0, sqlIns.Length - 1); db.ExecuteNonQuery(CommandType.Text, sqlIns); } } public static List GetDataListNew(string strCondition, int start, int limit, out int count, string sort) { var strSql = new StringBuilder(); strSql.Append(@"SELECT C.CUSTOMERNAME KeHuJianCheng, IC.DESCRIPTION KeHuQuanCheng, '' LanHuoRen, CD.DUIDATE DuiZhangRiQi, IC.CHIEF DuiZhangLianXiRen, IC.TEL DuiZhangLianXiDianHua, IC.EMAIL DuiZhangLianXiYouXiang, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=1 THEN C.AMOUNT ELSE 0 END) YingShouUSD, SUM(CASE WHEN C.CURRENCY = 'RMB' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuRMB, SUM(CASE WHEN C.CURRENCY = 'USD' AND C.FEETYPE=2 THEN C.AMOUNT ELSE 0 END) YingFuUSD, --查询字段 CD.OP DuiZhangRen, CD.DUINO DuiZhangBianHao, CD.DUINAME DuiZhangMingCheng, CD.REMARKS DuiZhangBeiZhu, VB.STLNAME JieFeiLeiXing FROM ch_fee C LEFT JOIN ch_dui CD on CD.DUINO = C.DEBITNO LEFT JOIN v_op_bs VB on VB.BSNO = C.BSNO LEFT JOIN info_client IC on IC.SHORTNAME = C.CUSTOMERNAME WHERE 1=1 "); if (!string.IsNullOrEmpty(strCondition)) { strSql.Append(" " + strCondition); } strSql.Append(@" GROUP BY C.CUSTOMERNAME,IC.DESCRIPTION,IC.CHIEF,IC.TEL,IC.EMAIL,CD.OP,CD.DUINO,CD.DUINAME,CD.REMARKS,CD.DUIDATE,VB.STLNAME "); if (!string.IsNullOrEmpty(sort)) { var so = JsonConvert.Deserialize>(sort); string orderbyStr = " ORDER BY "; foreach (var s in so) { orderbyStr += s.property + " " + s.direction + ","; } orderbyStr = orderbyStr.Substring(0, orderbyStr.Length - 1); strSql.Append(orderbyStr); } else { strSql.Append(" order by C.CUSTOMERNAME "); } int totalCount = 0; StringBuilder sb = PagerHelper.PageSQL(strSql.ToString(), start, limit, out totalCount); count = totalCount; return SetData(sb); } private static void InsertChDuiBill(List listdui) { Database db = DatabaseFactory.CreateDatabase(); List newList = listdui.Where((x, i) => listdui.FindIndex(z => z.BSNO == x.BSNO) == i).ToList(); StringBuilder insSb = new StringBuilder(); insSb.Append("insert into ch_dui_bill (DUINO,BSNO) values "); int cnt = 0; foreach (var item in newList) { insSb.Append("("); insSb.Append("'" + item.DuiNo + "',"); insSb.Append("'" + item.BSNO + "'"); insSb.Append("),"); //超过900行执行一次插入 if (cnt == 900) { string sql = insSb.ToString(); sql = sql.Substring(0, sql.Length - 1); db.ExecuteNonQuery(CommandType.Text, sql); insSb.Clear(); insSb.Append("insert into ch_dui_bill (DUINO,BSNO) values "); cnt = 0; } cnt++; } if (newList.Count>0) { string sqlIns = insSb.ToString(); sqlIns = sqlIns.Substring(0, sqlIns.Length - 1); db.ExecuteNonQuery(CommandType.Text, sqlIns); } } private static void InsertChDuiBill(string dMainId) { Database db = DatabaseFactory.CreateDatabase(); StringBuilder insSb = new StringBuilder(); insSb.Append("insert into ch_dui_bill (DUINO,BSNO) select distinct DEBITNO,BSNO FROM CH_fEE C WHERE EXISTS (SELECT 1 FROM ch_dui_main_dui d where d.duino=c.DEBITNO AND dMainId='" + dMainId+"')"); string sql = insSb.ToString(); db.ExecuteNonQuery(CommandType.Text, sql); } public static bool SaveDuiMain(MsChFeeYsAutoDuiMainModel md,out string mainid) { if (md.KaiChuanRiFrom == "") md.KaiChuanRiFrom = null; if (md.KaiChuanRiTo == "") md.KaiChuanRiTo = null; if (md.dMainId == ""||md.dMainId==null) { md.dMainId = Guid.NewGuid().ToString(); mainid = md.dMainId; StringBuilder sb = new StringBuilder(); sb.Append("insert into ch_dui_main "); sb.Append("(dMainId,mainDuiNo,mainDuiName,duiOp,description,KaiChuanRiFrom,KaiChuanRiTo,duiDate,DuiZhangKeHu,ShouFuFangXiang,JieFeiLeiXing,ShiFouYiKaiPiao,FeiYongZhuangTai,accDate_Min,accDate_Max,SALECORPID,CORPID,bibie,FEENAME,ISCHAOQI,ISZHIQI,EXCHANGERATE)"); sb.Append(" values ("); sb.Append("'" + md.dMainId + "',"); sb.Append("'" + md.mainDuiNo + "',"); sb.Append("'" + md.mainDuiName + "',"); sb.Append("'" + md.duiOp + "',"); sb.Append("'" + md.description + "',"); if (md.KaiChuanRiFrom==null) sb.Append("null,"); else sb.Append("'" + md.KaiChuanRiFrom + "',"); if (md.KaiChuanRiTo == null) sb.Append("null,"); else sb.Append("'" + md.KaiChuanRiTo + "',"); sb.Append("'" + md.duiDate + "',"); sb.Append("'" + md.DuiZhangKeHu + "',"); sb.Append("" + md.ShouFuFangXiang + ","); sb.Append("'" + md.JieFeiLeiXing + "',"); sb.Append("" + md.ShiFouYiKaiPiao + ","); sb.Append("" + md.FeiYongZhuangTai + ","); sb.Append("'" + md.accDate_Min+ "',"); sb.Append("'" + md.accDate_Max + "',"); sb.Append("'" + md.SALECORPID + "',"); sb.Append("'" + md.CORPID + "',"); sb.Append("'" + md.BiBie + "',"); sb.Append("'" + md.FEENAME + "',"); sb.Append("'" + md.ISCHAOQI + "',"); sb.Append("'" + md.ISZHIQI + "',"); sb.Append("'" + md.EXCHANGERATE + "'"); sb.Append(")"); Database db = DatabaseFactory.CreateDatabase(); return db.ExecuteNonQuery(CommandType.Text, sb.ToString()) > 0; } else { StringBuilder sb = new StringBuilder(); sb.Append("update ch_dui_main set "); sb.Append("mainDuiNo = '"+md.mainDuiNo+"',"); sb.Append("mainDuiName = '" + md.mainDuiName + "',"); sb.Append("description = '" + md.description + "',"); sb.Append("duiOp = '" + md.duiOp + "',"); sb.Append("duiDate = '" + md.duiDate + "',"); sb.Append("DuiZhangKeHu = '" + md.DuiZhangKeHu + "',"); sb.Append("ShouFuFangXiang = " + md.ShouFuFangXiang + ","); sb.Append("JieFeiLeiXing = '" + md.JieFeiLeiXing + "',"); sb.Append("ShiFouYiKaiPiao = " + md.ShiFouYiKaiPiao + ","); sb.Append("FeiYongZhuangTai = " + md.FeiYongZhuangTai + ","); sb.Append("accDate_Min = '" + md.accDate_Min + "',"); sb.Append("accDate_Max = '" + md.accDate_Max + "',"); sb.Append("SALECORPID = '" + md.SALECORPID + "',"); sb.Append("CORPID = '" + md.CORPID + "',"); sb.Append("bibie = '" + md.BiBie + "',"); sb.Append("FEENAME = '" + md.FEENAME + "',"); sb.Append("ISCHAOQI = " + md.ISCHAOQI + ","); sb.Append("ISZHIQI = " + md.ISZHIQI + ","); sb.Append("EXCHANGERATE = " + md.EXCHANGERATE + " "); sb.Append(" where dMainId = '" + md.dMainId + "'"); Database db = DatabaseFactory.CreateDatabase(); mainid = md.dMainId; return db.ExecuteNonQuery(CommandType.Text, sb.ToString()) > 0; } } public static bool CancelDui(List dataList,out string msg) { try { if (dataList.Count==0) { msg = "无可操作数据!"; return false; } Database db = DatabaseFactory.CreateDatabase(); StringBuilder sbDuiNo = new StringBuilder(); foreach (var item in dataList) { sbDuiNo.Append("'" + item.DuiZhangBianHao + "',"); } string duinos = sbDuiNo.ToString(); duinos = duinos.Substring(0, duinos.Length - 1); //删除ch_dui_main_dui关系表数据 string sql1 = "delete from ch_dui_main_dui where duino in (" + duinos + ")"; db.ExecuteNonQuery(CommandType.Text, sql1); //删除ch_dui string sql2 = "delete from ch_dui where duino in (" + duinos + ")"; db.ExecuteNonQuery(CommandType.Text, sql2); //删除ch_dui_bill string sql3 = "delete from ch_dui_bill where duino in (" + duinos + ")"; db.ExecuteNonQuery(CommandType.Text, sql3); //更新ch_fee string sql4 = "update ch_fee set debitno = '' , isdebit = 0 where debitno in (" + duinos + ")"; db.ExecuteNonQuery(CommandType.Text, sql4); msg = "取消成功!"; return true; } catch (Exception ex) { msg = ex.Message; return false; throw; } } public static bool UpdateReMarks(List list) { Database db = DatabaseFactory.CreateDatabase(); StringBuilder sb = new StringBuilder(); foreach (var item in list) { sb.Append("update ch_dui set REMARKS = '"+item.DuiZhangBeiZhu+"' "); sb.Append(" where duino = '"+item.DuiZhangBianHao+"' "); db.ExecuteNonQuery(CommandType.Text,sb.ToString()); sb.Clear(); } return false; } //DeleteMain public static bool DeleteMain(List list,out string msg) { Database db = DatabaseFactory.CreateDatabase(); string delids = ""; foreach (var item in list) { delids += "'"+item.dMainId+"',"; } if (delids!="") { delids = delids.Substring(0,delids.Length-1); if (checkHasDuiWithMainId(delids)) { msg = "存在已对账明细,无法删除!"; return false; } else { string sql = "delete from ch_dui_main where dMainId in (" + delids + ")"; int cnt= db.ExecuteNonQuery(CommandType.Text,sql); msg = cnt>0?"删除成功!":"删除失败!"; return cnt > 0; } } else { msg = "请选择要删除的数据!"; return false; } } private static bool checkHasDuiWithMainId(string mainids) { string sql = "select count(*) from ch_dui_main_dui where dMainId in ("+mainids+")"; Database db = DatabaseFactory.CreateDatabase(); int cnt = Convert.ToInt32(db.ExecuteScalar(CommandType.Text,sql)); return cnt > 0; } public static string GetSign(string userid) { string sql = "select mailsign from user_baseinfo where userid = '"+userid+"'"; Database db = DatabaseFactory.CreateDatabase(); var rst = db.ExecuteScalar(CommandType.Text, sql); if (rst==DBNull.Value) { return ""; } else { return rst.ToString(); } } public static bool SaveSign(string userid,string mailsign,out string msg) { string sql = "update user_baseinfo set mailsign = '"+mailsign+"' where userid = '" + userid + "'"; Database db = DatabaseFactory.CreateDatabase(); try { int rst = db.ExecuteNonQuery(CommandType.Text, sql); msg = rst > 0 ? "保存成功" : "保存失败"; return rst > 0; } catch (Exception e) { msg = e.Message; return false; throw; } } public static string GetDuiNameWithDuiNo(string duino) { string sql = "select mainDuiName from ch_dui_main where dMainId = (select top 1 dMainId from ch_dui_main_dui where duino = '"+duino+"')"; Database db = DatabaseFactory.CreateDatabase(); var rst = db.ExecuteScalar(CommandType.Text, sql); if (rst == DBNull.Value) { return ""; } else { return rst.ToString(); } } } }