using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using static Model.admin_log; using static regionController; public partial class admin_order_index : MyWeb.config { private Model.ezEntities _db = new Model.ezEntities(); public Dictionary _keyin1Item = null; protected string lastAddedNo; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Model.pro_order order = new Model.pro_order(); ArrayList options = order.keyin1_list(); foreach (Model.pro_order.keyin optionKey in options) { ListItem item = new ListItem(optionKey.Text, optionKey.Value); item.Attributes.Add("style", "color:" + optionKey.Color); s_keyin1.Items.Add(item); } _keyin1Item = publicFun.enum_desc(); //狀態 if (Session["LastAddedNo"] != null) { lastAddedNo = Session["LastAddedNo"].ToString(); Session.Remove("LastAddedNo"); } BuildKind(); } } #region 分類 public void BuildKind() { //國籍 s_country.Items.Clear(); s_country.Items.Add(new ListItem("請選擇", "")); var qry = _db.countries.OrderBy(x => x.range).ThenBy(x => x.name_en).ToList(); if (qry.Count > 0) { foreach (var x in qry) s_country.Items.Add(new ListItem(x.name_zh, x.ID)); } } #endregion #region 匯出Excel protected void export_Click(object sender, EventArgs e) { LinkButton btn = sender as LinkButton; if (btn == null) return; bool isPrintMode = (btn.ID == "print_management"); bool isExcelMode = (btn.ID == "excel_management" || btn.ID == "excel"); //查詢要匯出的資料 string _query = ""; // 紀錄匯出條件 //var list = searchData(ref _query, isManagementMode); if (isExcelMode) { int selYear = !string.IsNullOrEmpty(hid_print_year.Value) ? int.Parse(hid_print_year.Value) : 0; int selMonth = !string.IsNullOrEmpty(hid_print_month.Value) ? int.Parse(hid_print_month.Value) : 0; int selSeason = !string.IsNullOrEmpty(hid_print_season.Value) ? int.Parse(hid_print_season.Value) : 0; string selMode = !string.IsNullOrEmpty(hid_print_mode.Value) ? hid_print_mode.Value : ""; bool chkHasAct = !string.IsNullOrEmpty(hid_chk_hasact.Value) && Convert.ToBoolean(hid_chk_hasact.Value); bool chkNoAct = !string.IsNullOrEmpty(hid_chk_noact.Value) && Convert.ToBoolean(hid_chk_noact.Value); int selAct = !string.IsNullOrEmpty(hid_select_act.Value) ? int.Parse(hid_select_act.Value) : 0; int selActItem = !string.IsNullOrEmpty(hid_select_actitem.Value) ? int.Parse(hid_select_actitem.Value) : 0; var qry = _db.pro_order.AsQueryable(); if (selYear > 0) { qry = qry.Where(o => o.up_time.HasValue && o.up_time.Value.Year == selYear); _query += "年份:" + selYear + "\n"; } if (selMode == "mm" && selMonth > 0) { qry = qry.Where(o => o.up_time.HasValue && o.up_time.Value.Month == selMonth); _query += "月份:" + selMonth + "\n"; } if (selMode == "ss" && selSeason > 0) { if (selSeason == 1) { qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 1 || o.up_time.Value.Month == 2 || o.up_time.Value.Month == 3); } else if (selSeason == 2) { qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 4 || o.up_time.Value.Month == 5 || o.up_time.Value.Month == 6); } else if (selSeason == 3) { qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 7 || o.up_time.Value.Month == 8 || o.up_time.Value.Month == 9); } else if (selSeason == 4) { qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 10 || o.up_time.Value.Month == 11 || o.up_time.Value.Month == 12); } _query += "季度:" + selSeason + "\n"; } if (chkHasAct) { if(selAct > 0) { var actSubject = _db.activities.Where(a => a.num == selAct).Select(a => a.subject).FirstOrDefault(); _query += $"活動報名: {actSubject}\n"; } else { _query += $"活動報名\n"; } if (chkNoAct) { _query += "非活動報名\n"; if (selAct > 0) qry = qry.Where(o => o.activity_num.HasValue && o.activity_num.Value == selAct); } else { qry = qry.Where(o => o.activity_num.HasValue); if (selAct > 0) qry = qry.Where(o => o.activity_num.Value == selAct); } } else { if (chkNoAct) { qry = qry.Where(o => o.activity_num == null); _query += "非活動報名\n"; } } if (selActItem > 0) qry = qry.Where(o => o.pro_order_detail.Where(f2 => f2.actItem_num.HasValue && f2.actItem_num.Value == selActItem).Count() > 0); if (selYear > 0) qry = qry.OrderByDescending(o => o.activity != null ? o.activity.startDate_solar : null).ThenByDescending(o => o.up_time).ThenByDescending(o => o.order_no); else qry = qry.OrderByDescending(o => o.order_no); MyWeb.encrypt encrypt = new MyWeb.encrypt(); var tdesc = publicFun.enum_desc(); var bedDt = _db.bed_order_detail.AsQueryable();//掛單明細 //紀錄匯出條件 //var list = qry.ToList(); var list = qry.GroupJoin( _db.pro_order_detail, o => o.order_no, p => p.order_no, (o, c) => new { //訂單資料 order_no = o.order_no, up_time = o.up_time, keyin1 = o.keyin1, f_num = o.follower != null ? o.follower.u_name : "", //姓名/名稱 phone = o.phone, activity_num = o.activity_num.HasValue ? o.activity.subject : "", address = o.address, demo = o.demo, c }).SelectMany(o => o.c.DefaultIfEmpty(), (o, d) => //SelectMany 展開 new { //訂單資料 order_no = o.order_no, up_time = o.up_time, keyin1 = o.keyin1, f_num = o.f_num, //姓名/名稱 phone = o.phone, activity_num = o.activity_num, address = o.address, demo = o.demo, //訂單明細 //使用DefaultIfEmpty 因匿名型別無法輸出NULL(無法轉換成強型別),需特別注意Null的處理 d_actItem_num = d == null ? "" : (d.actItem_num.HasValue ? d.actItem.subject : ""), //項目名稱 d_category = d == null ? "" : (d.actItem_num.HasValue ? d.actItem.category.ToString() : ""), d_f_num = d == null ? "" : (d.f_num.HasValue ? d.follower.u_name : ""), //姓名 d_address = d == null ? "" : d.address, d_from_id = d == null ? "" : (d.from_id.HasValue ? d.follower1.u_name : ""), //陽上/報恩者 d_f_num_tablet = d == null ? "" : d.f_num_tablet, d_start_date = d == null ? (DateTime?)null : d.start_date, //開始日期 d_due_date = d == null ? (DateTime?)null : d.due_date, //期滿日期 d_extend_date = d == null ? (DateTime?)null : d.extend_date, //應續約日 d_price = d == null ? (float?)null : d.price, //預設金額 d_qty = d == null ? "" : (d.qty.HasValue ? d.qty.Value.ToString() : "0"), //數量 d_writeBedQty = d == null ? 0 : bedDt.Where(b => (b.bed_order.o_detail_id.Value == d.num) && b.checkIn_date.HasValue && b.bed_kind_detail_id.HasValue).Count(), //已劃數量 d_notBedQty = d == null ? 0 : bedDt.Where(b => b.bed_order.o_detail_id.Value == d.num && (!b.checkIn_date.HasValue || !b.bed_kind_detail_id.HasValue)).Count(), //未劃數量 d_pay = d == null ? "" : (d.pay.HasValue ? d.pay.Value.ToString() : "0"), //已收金額 d_pay_date = d == null ? (DateTime?)null : d.start_date, //付款期限 d_keyin1 = d == null ? (int?)null : d.keyin1, d_demo = d == null ? "" : d.demo, //狀態備註 }).ToList(); var memoryStream = new MemoryStream(); if (list.Count > 0) { using (var doc = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var wb = doc.AddWorkbookPart(); wb.Workbook = new Workbook(); var sheets = wb.Workbook.AppendChild(new Sheets()); //建立第一個頁籤 var ws = wb.AddNewPart(); ws.Worksheet = new Worksheet(); sheets.Append(new Sheet() { Id = wb.GetIdOfPart(ws), SheetId = 1, Name = "報名" }); //設定欄寬 var cu = new Columns(); cu.Append( new Column { Min = 1, Max = 1, Width = 15, CustomWidth = true }, new Column { Min = 2, Max = 4, Width = 10, CustomWidth = true }, new Column { Min = 5, Max = 5, Width = 15, CustomWidth = true }, new Column { Min = 6, Max = 8, Width = 25, CustomWidth = true }, new Column { Min = 9, Max = 9, Width = 15, CustomWidth = true }, new Column { Min = 10, Max = 10, Width = 10, CustomWidth = true }, new Column { Min = 11, Max = 11, Width = 25, CustomWidth = true }, new Column { Min = 12, Max = 16, Width = 10, CustomWidth = true }, new Column { Min = 17, Max = 20, Width = 10, CustomWidth = true } ); ws.Worksheet.Append(cu); //建立資料頁 var sd = new SheetData(); ws.Worksheet.AppendChild(sd); //第一列資料 var tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue("單號"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("單據狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("姓名/名稱"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("聯絡電話"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名活動"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("收件地址"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("備註"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("項目名稱"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("姓名"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("代表地址"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("標題"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("陽上/報恩者"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("開始日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("期滿日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("應續約日"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("劃位狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("預設金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("數量"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("小計"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("已收金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("未收金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("付款期限"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("狀態備註"), DataType = CellValues.String } ); sd.AppendChild(tr); foreach (var item in list) { string midNamesResult = ""; string leftNamesResult = ""; string jsonString = item.d_f_num_tablet?.ToString() ?? ""; try { var jo = JObject.Parse(jsonString); // 標題 var midList = jo["mid_items"]? .Select(i => (string)i["fam_name"]) .Where(name => !string.IsNullOrEmpty(name)) .ToList(); if (midList != null && midList.Any()) { midNamesResult = string.Join(", ", midList); } // 陽上 var leftList = jo["left_items"]? .Select(i => (string)i["fam_name"]) .Where(name => !string.IsNullOrEmpty(name)) .ToList(); if (leftList != null && leftList.Any()) { leftNamesResult = string.Join(", ", leftList); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"JSON 解析失敗 (訂單:{item.order_no}): {ex.Message}"); } //新增資料列 tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(item.order_no), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.up_time?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(Model.pro_order.keyin1_value_to_text(item.keyin1)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.f_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(encrypt.DecryptAutoKey(item.phone)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.activity_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.address), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.demo), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_actItem_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_f_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_address), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(midNamesResult), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(leftNamesResult), DataType = CellValues.String }, //new Cell() { CellValue = new CellValue(item.d_from_id), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_start_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_due_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_extend_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue((Val(item.d_category) == (int)Model.activity.category.Order) ? (item.d_notBedQty + "/" + item.d_writeBedQty) : ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(item.d_price)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_qty), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(ValFloat(item.d_price) * Val(item.d_qty))), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(item.d_pay)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(ValFloat(item.d_price) * Val(item.d_qty) - ValFloat(item.d_pay))), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_pay_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_keyin1.HasValue ? tdesc[item.d_keyin1.Value] : ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_demo), DataType = CellValues.String } ); sd.AppendChild(tr); } //空一列 tr = new Row(); sd.AppendChild(tr); //匯出資訊 string _data = "匯出時間 : " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); _data += " " + admin.info.u_id; tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(_data), DataType = CellValues.String } ); sd.AppendChild(tr); _data = "匯出條件 : " + (!isStrNull(_query) ? _query : "-"); tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(_data), DataType = CellValues.String } ); sd.AppendChild(tr); Model.admin_log admin_log = new Model.admin_log(); admin_log.writeLog(admin.info.u_id, (int)Model.admin_log.Systems.Order, (int)Model.admin_log.Status.Excel, admin_log.LogViewBtn(list.Select(x => x.order_no).ToList())); } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=報名.xlsx"); HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray()); HttpContext.Current.Response.End(); hid_err_msg.Value = "success"; } else { hid_err_msg.Value = "nodata"; } } else if (isPrintMode) { int selYear = !string.IsNullOrEmpty(hid_print_year.Value) ? int.Parse(hid_print_year.Value) : 0; int selMonth = !string.IsNullOrEmpty(hid_print_month.Value) ? int.Parse(hid_print_month.Value) : 0; int selSeason = !string.IsNullOrEmpty(hid_print_season.Value) ? int.Parse(hid_print_season.Value) : 0; string selMode = !string.IsNullOrEmpty(hid_print_mode.Value) ? hid_print_mode.Value : ""; bool chkHasAct = !string.IsNullOrEmpty(hid_chk_hasact.Value) && Convert.ToBoolean(hid_chk_hasact.Value); bool chkNoAct = !string.IsNullOrEmpty(hid_chk_noact.Value) && Convert.ToBoolean(hid_chk_noact.Value); int selAct = !string.IsNullOrEmpty(hid_select_act.Value) ? int.Parse(hid_select_act.Value) : -1; int selActItem = !string.IsNullOrEmpty(hid_select_actitem.Value) ? int.Parse(hid_select_actitem.Value) : -1; string urlParams = !string.IsNullOrEmpty(hid_qry.Value) ? hid_qry.Value : ""; var qry = _db.pro_order.AsQueryable(); if (selYear > 0) qry = qry.Where(o => o.up_time.HasValue && o.up_time.Value.Year == selYear); if (selMode == "mm" && selMonth > 0) qry = qry.Where(o => o.up_time.HasValue && o.up_time.Value.Month == selMonth); else if (selMode == "ss" && selSeason > 0) { if (selSeason == 1) qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 1 || o.up_time.Value.Month == 2 || o.up_time.Value.Month == 3); else if (selSeason == 2) qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 4 || o.up_time.Value.Month == 5 || o.up_time.Value.Month == 6); else if (selSeason == 3) qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 7 || o.up_time.Value.Month == 8 || o.up_time.Value.Month == 9); else if (selSeason == 4) qry = qry.Where(o => o.up_time.HasValue) .Where(o => o.up_time.Value.Month == 10 || o.up_time.Value.Month == 11 || o.up_time.Value.Month == 12); } if (chkHasAct) { if (chkNoAct) { if (selAct >= 0) qry = qry.Where(o => o.activity_num.HasValue && o.activity_num.Value == selAct); } else { qry = qry.Where(o => o.activity_num.HasValue); if (selAct >= 0) qry = qry.Where(o => o.activity_num.Value == selAct); } } else { if (chkNoAct) qry = qry.Where(o => o.activity_num == null); } if (selActItem >= 0) { qry = qry.Where(o => o.pro_order_detail.Where(f2 => f2.actItem_num.HasValue && f2.actItem_num.Value == selActItem).Count() > 0); } var count = qry.Count(); if (count > 0) { hid_err_msg.Value = "success"; string script = $@"var otherWin = window.open('print.aspx{urlParams}', '列印報名資料', 'noopener,noreferrer');"; ScriptManager.RegisterStartupScript(this, GetType(), "ExecutePrint", script, true); } else { hid_err_msg.Value = "nodata"; } //var qry = _db.followers.AsQueryable(); //if (selYear > 0) //{ // urlParams += "&year=" + selYear; //} //if (selMode == "mm" && selMonth > 0) //{ // urlParams += "&month=" + selMonth; //} //else if (selMode == "ss" && selSeason > 0) //{ // urlParams += "&season=" + selSeason; //} //if (list.Count > 0) //{ // hid_err_msg.Value = "success"; // hid_print_year.Value = selYear.ToString(); // hid_print_month.Value = selMonth.ToString(); // hid_print_season.Value = selSeason.ToString(); // hid_print_mode.Value = selMode; // string script = $@"window.open('print.aspx?{urlParams}&mode={selMode}', '列印信眾資料');"; // ScriptManager.RegisterStartupScript(this, GetType(), "ExecutePrint", script, true); //} //else //{ // hid_err_msg.Value = "nodata"; // string script = $@" // var win = window.open('', '列印信眾資料'); // if (win) win.close()"; // ScriptManager.RegisterStartupScript(this, GetType(), "CancelPrint", script, true); //} } } protected void excel_Click(object sender, EventArgs e) { var memoryStream = new MemoryStream(); using (var doc = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var wb = doc.AddWorkbookPart(); wb.Workbook = new Workbook(); var sheets = wb.Workbook.AppendChild(new Sheets()); //建立第一個頁籤 var ws = wb.AddNewPart(); ws.Worksheet = new Worksheet(); sheets.Append(new Sheet() { Id = wb.GetIdOfPart(ws), SheetId = 1, Name = "報名" }); //設定欄寬 var cu = new Columns(); cu.Append( new Column { Min = 1, Max = 1, Width = 15, CustomWidth = true }, new Column { Min = 2, Max = 4, Width = 10, CustomWidth = true }, new Column { Min = 5, Max = 5, Width = 15, CustomWidth = true }, new Column { Min = 6, Max = 8, Width = 25, CustomWidth = true }, new Column { Min = 9, Max = 9, Width = 15, CustomWidth = true }, new Column { Min = 10, Max = 10, Width = 10, CustomWidth = true }, new Column { Min = 11, Max = 11, Width = 25, CustomWidth = true }, new Column { Min = 12, Max = 16, Width = 10, CustomWidth = true }, new Column { Min = 17, Max = 20, Width = 10, CustomWidth = true } ); ws.Worksheet.Append(cu); //建立資料頁 var sd = new SheetData(); ws.Worksheet.AppendChild(sd); //第一列資料 var tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue("單號"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("單據狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("姓名/名稱"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("聯絡電話"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名活動"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("收件地址"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("備註"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("項目名稱"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("姓名"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("代表地址"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("標題"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("陽上/報恩者"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("開始日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("期滿日期"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("應續約日"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("劃位狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("預設金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("數量"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("小計"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("已收金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("未收金額"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("付款期限"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("報名狀態"), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("狀態備註"), DataType = CellValues.String } ); sd.AppendChild(tr); //查詢要匯出的資料 // ❌ 錯誤寫法: var aIDt = _db.actItems.Where(f => f.subject.Contains(s_actItemTxt.Value.Trim())).Select(f => f.num.ToString()); // 改為整數陣列,避免後續查詢中使用 .ToString() var aIDt = _db.actItems.Where(f => f.subject.Contains(s_actItemTxt.Value.Trim())).Select(f => f.num).ToArray();//品項 var qry = _db.pro_order.AsQueryable(); string _query = ""; // 紀錄匯出條件 if (!isStrNull(s_order_no.Value)) { _query += "單號:" + s_order_no.Value + "\n"; qry = qry.Where(o => o.order_no.Contains(s_order_no.Value.Trim())); } if (!isStrNull(s_u_name.Value)) { _query += "姓名/名稱:" + s_u_name.Value + "\n"; qry = qry.Where(o => o.f_num.HasValue && o.follower.u_name.Contains(s_u_name.Value.Trim())); } if (!isStrNull(s_introducerTxt.Value)) { _query += "介紹人:" + s_introducerTxt.Value + "\n"; qry = qry.Where(o => o.f_num.HasValue && o.follower1.u_name.Contains(s_introducerTxt.Value.Trim())); } if (!isStrNull(s_subject.Value)) { _query += "報名活動:" + s_subject.Value + "\n"; qry = qry.Where(o => o.activity_num.HasValue && o.activity.subject.Contains(s_subject.Value.Trim())); } if (!isStrNull(s_actItemTxt.Value)) { // ❌ 錯誤寫法: qry = qry.Where(o => o.pro_order_detail.Where(f2 => f2.order_no == o.order_no && aIDt.ToArray().Contains(f2.actItem_num.ToString())).Count() > 0); // ✅ 實際比較:僅在 actItem_num 有值時才與整數陣列比對 _query += "品項:" + s_actItemTxt.Value + "\n"; qry = qry.Where(o => o.pro_order_detail.Any(f2 => f2.order_no == o.order_no && f2.actItem_num.HasValue && aIDt.Contains(f2.actItem_num.Value))); } if (!isStrNull(s_keyin1.SelectedValue)) { _query += $"單據狀態:{Model.pro_order.keyin1_value_to_text(s_keyin1.SelectedValue)}\n"; qry = qry.Where(o => o.keyin1 == s_keyin1.SelectedValue); } if (!isStrNull(s_up_time1.Value) && isDate(s_up_time1.Value)) { _query += "報名日期(起):" + s_up_time1.Value.Trim() + "\n"; var tmp_s_up_time1 = ValDate(s_up_time1.Value); qry = qry.Where(o => o.up_time >= tmp_s_up_time1); } if (!isStrNull(s_up_time2.Value) && isDate(s_up_time2.Value)) { _query += "報名日期(訖):" + s_up_time2.Value.Trim() + "\n"; var tmp_s_up_time2 = Convert.ToDateTime(s_up_time2.Value).AddDays(1); qry = qry.Where(o => o.up_time < tmp_s_up_time2); } qry = qry.OrderByDescending(o => o.reg_time); MyWeb.encrypt encrypt = new MyWeb.encrypt(); var tdesc = publicFun.enum_desc(); var bedDt = _db.bed_order_detail.AsQueryable();//掛單明細 //left join 使用 GroupJoin //var list = qry.Join var list = qry.GroupJoin( _db.pro_order_detail, o => o.order_no, p => p.order_no, (o, c) => new { //訂單資料 order_no = o.order_no, up_time = o.up_time, keyin1 = o.keyin1, f_num = o.follower != null ? o.follower.u_name : "", //姓名/名稱 phone = o.phone, activity_num = o.activity_num.HasValue ? o.activity.subject : "", address = o.address, demo = o.demo, c }).SelectMany(o => o.c.DefaultIfEmpty(), (o, d) => //SelectMany 展開 new { //訂單資料 order_no = o.order_no, up_time = o.up_time, keyin1 = o.keyin1, f_num = o.f_num, //姓名/名稱 phone = o.phone, activity_num = o.activity_num, address = o.address, demo = o.demo, //訂單明細 //使用DefaultIfEmpty 因匿名型別無法輸出NULL(無法轉換成強型別),需特別注意Null的處理 d_actItem_num = d == null ? "" : (d.actItem_num.HasValue ? d.actItem.subject : ""), //項目名稱 d_category = d == null ? "" : (d.actItem_num.HasValue ? d.actItem.category.ToString() : ""), d_f_num = d == null ? "" : (d.f_num.HasValue ? d.follower.u_name : ""), //姓名 d_address = d == null ? "" : d.address, d_from_id = d == null ? "" : (d.from_id.HasValue ? d.follower1.u_name : ""), //陽上/報恩者 d_f_num_tablet = d == null ? "" : d.f_num_tablet, d_start_date = d == null ? (DateTime?)null : d.start_date, //開始日期 d_due_date = d == null ? (DateTime?)null : d.due_date, //期滿日期 d_extend_date = d == null ? (DateTime?)null : d.extend_date, //應續約日 d_price = d == null ? (float?)null : d.price, //預設金額 d_qty = d == null ? "" : (d.qty.HasValue ? d.qty.Value.ToString() : "0"), //數量 d_writeBedQty = d == null ? 0 : bedDt.Where(b => (b.bed_order.o_detail_id.Value == d.num) && b.checkIn_date.HasValue && b.bed_kind_detail_id.HasValue).Count(), //已劃數量 d_notBedQty = d == null ? 0 : bedDt.Where(b => b.bed_order.o_detail_id.Value == d.num && (!b.checkIn_date.HasValue || !b.bed_kind_detail_id.HasValue)).Count(), //未劃數量 d_pay = d == null ? "" : (d.pay.HasValue ? d.pay.Value.ToString() : "0"), //已收金額 d_pay_date = d == null ? (DateTime?)null : d.start_date, //付款期限 d_keyin1 = d == null ? (int?)null : d.keyin1, d_demo = d == null ? "" : d.demo, //狀態備註 }).ToList(); //也可使用查詢式 //try ////{ // var listQ = from o in qry // join p in _db.pro_order_detail // on new // { // order_no = o.order_no, // } equals // new { p.order_no } // into subGrp //into == // from d in subGrp.DefaultIfEmpty() // select new // { // //訂單資料 // order_no = o.order_no, // up_time = o.up_time, // f_num = o.follower.u_name, //姓名/名稱 // ... // //訂單明細 // //使用DefaultIfEmpty 因匿名型別無法輸出NULL(無法轉換成強型別),需特別注意Null的處理 // d_actItem_num = d == null? "" :(d.actItem_num.HasValue ? d.actItem.subject : ""), //項目名稱 // d_f_num = d == null ? "" :( d.f_num.HasValue ? d.follower.u_name : ""), //姓名 // ... // }; // var list = listQ.ToList(); //} //catch (Exception ex) //{ // Response.Write(ex.Message); //} if (list.Count > 0) { foreach (var item in list) { string midNamesResult = ""; string leftNamesResult = ""; string jsonString = item.d_f_num_tablet?.ToString() ?? ""; try { var jo = JObject.Parse(jsonString); // 標題 var midList = jo["mid_items"]? .Select(i => (string)i["fam_name"]) .Where(name => !string.IsNullOrEmpty(name)) .ToList(); if (midList != null && midList.Any()) { midNamesResult = string.Join(", ", midList); } // 陽上 var leftList = jo["left_items"]? .Select(i => (string)i["fam_name"]) .Where(name => !string.IsNullOrEmpty(name)) .ToList(); if (leftList != null && leftList.Any()) { leftNamesResult = string.Join(", ", leftList); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"JSON 解析失敗 (訂單:{item.order_no}): {ex.Message}"); } //新增資料列 tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(item.order_no), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.up_time?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(Model.pro_order.keyin1_value_to_text(item.keyin1)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.f_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(encrypt.DecryptAutoKey(item.phone)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.activity_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.address), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.demo), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_actItem_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_f_num), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_address), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(midNamesResult), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(leftNamesResult), DataType = CellValues.String }, //new Cell() { CellValue = new CellValue(item.d_from_id), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_start_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_due_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_extend_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue((Val(item.d_category) == (int)Model.activity.category.Order) ? (item.d_notBedQty + "/" + item.d_writeBedQty) : ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(item.d_price)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_qty), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(ValFloat(item.d_price) * Val(item.d_qty))), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(item.d_pay)), DataType = CellValues.String }, new Cell() { CellValue = new CellValue("$" + ValMoney(ValFloat(item.d_price) * Val(item.d_qty) - ValFloat(item.d_pay))), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_pay_date?.ToString("yyyy/MM/dd") ?? ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_keyin1.HasValue ? tdesc[item.d_keyin1.Value] : ""), DataType = CellValues.String }, new Cell() { CellValue = new CellValue(item.d_demo), DataType = CellValues.String } ); sd.AppendChild(tr); } //空一列 tr = new Row(); sd.AppendChild(tr); //匯出資訊 string _data = "匯出時間 : " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); _data += " " + admin.info.u_id; tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(_data), DataType = CellValues.String } ); sd.AppendChild(tr); _data = "匯出條件 : " + (!isStrNull(_query) ? _query : "-"); tr = new Row(); tr.Append( new Cell() { CellValue = new CellValue(_data), DataType = CellValues.String } ); sd.AppendChild(tr); Model.admin_log admin_log = new Model.admin_log(); admin_log.writeLog(admin.info.u_id, (int)Model.admin_log.Systems.Order, (int)Model.admin_log.Status.Excel, admin_log.LogViewBtn(list.Select(x => x.order_no).ToList())); // 合并具有相同单号的行 //string orderNumber = ""; //int startRow = 1; //int endRow = 1; //int nowRow = 1; //foreach (var kvp in list) //{ // if(orderNumber == "" || orderNumber != kvp.order_no) // { // orderNumber = kvp.order_no; // int _count = list.Where(x => x.order_no == orderNumber).Count(); // if (_count > 1) // { // endRow += _count; // var mergeCells = new MergeCells(); // string startCellReference = GetCellReference(1, startRow); // string endCellReference = GetCellReference(1, endRow); // if (startCellReference != endCellReference) // mergeCells.Append(new MergeCell() { Reference = new StringValue($"{startCellReference}:{endCellReference}") }); // } // startRow += _count; // endRow = startRow; // } // else // { // startRow ++; // endRow = startRow; // } // nowRow++; //} } } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=報名.xlsx"); HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray()); HttpContext.Current.Response.End(); } private string GetCellReference(int column, int row) { int dividend = column; string cellReference = string.Empty; while (dividend > 0) { int modulo = (dividend - 1) % 26; char columnChar = (char)('A' + modulo); cellReference = columnChar + cellReference; dividend = (dividend - modulo) / 26; } return cellReference + row.ToString(); } #endregion }