Files
17168ERP/web/admin/print/exportExcel.aspx.cs
2025-08-29 01:27:25 +08:00

326 lines
13 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using static Model.admin_log;
using OfficeOpenXml;
using System.IO;
using System.Web;
public partial class admin_print_exportExcel : MyWeb.function
{
private Model.ezEntities _db = new Model.ezEntities();
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write("item:"+Request["item"]+"<br>");
//Response.Write("file:"+Request["file"]+"<br>");
//Response.Write("list:"+Request["list"]+"<br>");
if (!IsPostBack)
{
if (Request.HttpMethod == "POST")
{
if (!String.IsNullOrEmpty(Request["item"]) && !String.IsNullOrEmpty(Request["file"]))
{
var _details= Newtonsoft.Json.JsonConvert.DeserializeObject<int[]>(Request["list"]);
//var orderItem = _db.pro_order_detail.AsEnumerable().Where(q =>_details.Contains(q.num) ).ToList();
var orderItem = _db.pro_order_detail.Where(q =>_details.Contains(q.num) ).ToList();
ExcelExporter.ExportOrdersToExcel(HttpContext.Current, orderItem);
}
else
{
Response.Clear();
Response.StatusCode = 404;
Response.End();
}
}
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int _detail = (int)e.Item.DataItem;
var orderItem = _db.pro_order_detail.AsEnumerable().Where(q => q.num == _detail).FirstOrDefault();
int _num = Convert.ToInt32(Request["file"]);
var qry = _db.files.AsEnumerable();
var prod = qry.Where(q => q.num == _num).FirstOrDefault();
if (prod != null && orderItem != null)
{
string _word = prod.word;
string file_cuz_column = prod.customize_data ?? "";
//格式->品項->活動->信眾->報名->報名明細
//上至下層依序讀入各自定義欄位:名稱及值
List<string> newStrList = new List<string>(); //參數集合((名稱及值​
if (!string.IsNullOrEmpty(file_cuz_column))
{
proCuzData(newStrList, file_cuz_column);
}
if (orderItem.actItem_num.HasValue && !string.IsNullOrEmpty(orderItem.actItem.customize_data))
{
proCuzData(newStrList, orderItem.actItem.customize_data);
}
if (orderItem.pro_order.activity_num.HasValue && !string.IsNullOrEmpty(orderItem.pro_order.activity.customize_data))
{
proCuzData(newStrList, orderItem.pro_order.activity.customize_data);
}
//if (orderItem.f_num.HasValue && !string.IsNullOrEmpty(orderItem.follower.customize_data))
if (orderItem.pro_order.f_num.HasValue && !string.IsNullOrEmpty(orderItem.pro_order.follower.customize_data))//訂單主黨的姓名/名稱?
{
proCuzData(newStrList, orderItem.pro_order.follower.customize_data);
}
if (!string.IsNullOrEmpty(orderItem.pro_order.customize_data))
{
proCuzData(newStrList, orderItem.pro_order.customize_data);
}
if (!string.IsNullOrEmpty(orderItem.customize_data))
{
proCuzData(newStrList, orderItem.customize_data);
}
string detail_data = newStrList.Count > 0 ? string.Join("\r\n", newStrList) : "";//參數集合((名稱及值​
string[] k = detail_data.Split('$');
for (int i = 0; i < k.Length; i++)
{
if (!String.IsNullOrEmpty(k[i]))
{
string[] _v = k[i].Split(':');
_word = _word.Replace("{$" + _v[0] + "}", _v[1].Trim());
}
}
//加入固定欄位變數定義
//日期
string[] _type = { "zh", "min", "lunar" };
_word = _word.Replace("{pro_order.up_time}", !isStrNull(orderItem.pro_order.up_time) ? proDateStr(orderItem.pro_order.up_time.Value, "") : "");
foreach (var tt in _type)
{
_word = _word.Replace("{pro_order.up_time." + tt + "}", !isStrNull(orderItem.pro_order.up_time) ? proDateStr(orderItem.pro_order.up_time.Value, tt) : "");
}
if (orderItem.pro_order.activity != null)
{
_word = _word.Replace("{activity.startDate_solar}", !isStrNull(orderItem.pro_order.activity.startDate_solar) ? proDateStr(orderItem.pro_order.activity.startDate_solar.Value, "") : "");
foreach (var tt in _type)
{
_word = _word.Replace("{activity.startDate_solar." + tt + "}", !isStrNull(orderItem.pro_order.activity.startDate_solar) ? proDateStr(orderItem.pro_order.activity.startDate_solar.Value, tt) : "");
}
_word = _word.Replace("{activity.endDate_solar}", !isStrNull(orderItem.pro_order.activity.endDate_solar) ? proDateStr(orderItem.pro_order.activity.endDate_solar.Value, "") : "");
foreach (var tt in _type)
{
_word = _word.Replace("{activity.endDate_solar." + tt + "}", !isStrNull(orderItem.pro_order.activity.endDate_solar) ? proDateStr(orderItem.pro_order.activity.endDate_solar.Value, tt) : "");
}
}
//金額
_word = _word.Replace("{pro_order_detail.price}", !isStrNull(orderItem.price) ? ValMoneyCh(orderItem.price.Value) : "");
try
{
_word = _word.Replace("{pro_order.order_no}", !isStrNull(orderItem.order_no) ? orderItem.order_no : "");
//信眾編號
_word = _word.Replace("{follower.f_number}", !isStrNull(orderItem.pro_order.follower.f_number) ? orderItem.pro_order.follower.f_number : "");
//牌位中間標題(消災/超薦)
_word = _word.Replace("{orderItem.f_num_tablet}", !isStrNull(orderItem.f_num_tablet) ? orderItem.f_num_tablet : "");
//牌位左側標題(陽上/報恩)
_word = _word.Replace("{orderItem.from_id_tablet}", !isStrNull(orderItem.from_id_tablet) ? orderItem.from_id_tablet : "");
}
catch (Exception ex)
{
}
_word=ReplacePlaceholders(_word);
((Literal)e.Item.FindControl("word")).Text = _word;
}
}
protected void proCuzData(List<string> _column, string this_data)
{
if (!string.IsNullOrWhiteSpace(this_data))
{
string[] _list = this_data.Split('$');
for (int i = 0; i < _list.Length; i++)
{
if (!string.IsNullOrWhiteSpace(_list[i]))
{
string[] _v = _list[i].Split(':');
//比對
bool isExist = false; //參數是否已存在
for (int j = 0; j < _column.Count; j++)
{
string[] _y = _column[j].Split(':');
if ("$" + _v[0] == _y[0])
{
isExist = true;
if (!string.IsNullOrWhiteSpace(_v[1]))
_column[j] = "$" + _list[i];
break;
}
}
if (!isExist)
{
//加入參數
_column.Add("$" + _list[i]);
}
}
}
}
}
private static string ReplacePlaceholders(string input)
{
string pattern = @"\{\$[^\}]+\}";
return Regex.Replace(input, pattern, "");
}
#region
protected string proDateStr(DateTime date, string type)
{
string txt = "";
if (type == "")
{
txt = date.ToString("yyyy/MM/dd");
}
else if (type == "zh")//西元中文日期
{
//将日期转换成中文显示
string year = date.Year.ToString();
string month = date.Month.ToString("00");
//if (int.Parse(month) < 10) { month = "0" + month; }
string days = date.Day.ToString("00");
//if (int.Parse(days) < 10) { days = "0" + days; }
txt = GetChineseDateNumber2(year, month, days);
}
else if (type == "min")//民國中文日期
{
//轉成民國年
CultureInfo culture = new CultureInfo("zh-TW");
culture.DateTimeFormat.Calendar = new TaiwanCalendar();
string _cul = date.ToString("yyy/MM/dd", culture);
string[] k = _cul.Split('/');
//System.Globalization.TaiwanCalendar tc = new System.Globalization.TaiwanCalendar();
//tc.GetYear(date), tc.GetMonth(date), tc.GetDayOfMonth(date)
if (k.Length == 3)
{
txt = GetChineseDateNumber2(k[0], k[1], k[2]);
}
}
else if (type == "lunar")//民國年農曆日期
{
//轉成農曆年
ChineseLunisolarCalendar chineseDate = new ChineseLunisolarCalendar();
int yy = chineseDate.GetYear(date) - 1911;
int mm = chineseDate.GetMonth(date);
int dd = chineseDate.GetDayOfMonth(date);
txt = GetChineseDateNumber2(yy.ToString(), mm.ToString("00"), dd.ToString("00"));
}
return txt;
}
static string GetChineseDateNumber2(string year, string month, string days)
{
//StringBuilder sb = new StringBuilder();
List<string> sb = new List<string>();
for (int i = 0; i < year.Length; i++)//年转换
{
//sb.Append(GetChineseDateNumber(int.Parse(year[i].ToString())));
sb.Add(GetChineseDateNumber(int.Parse(year[i].ToString())));
}
sb.Add("年");
for (int r = 0; r < month.Length; r++)//月转换
{
sb.Add(GetChineseDateNumber(int.Parse(month[r].ToString())));
}
sb.Add("月");
for (int t = 0; t < days.Length; t++)//日转换
{
sb.Add(GetChineseDateNumber(int.Parse(days[t].ToString())));
}
sb.Add("日");
//return sb.ToString();
return string.Join("", sb);
}
static string GetChineseDateNumber(int dateStr)
{
string[] cns = new string[] {
"零", "一", "二", "三", "四", "五", "六", "七", "八", "九",
"十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九",
"二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九",
"三十", "三十一"
};
return cns[dateStr];
}
#endregion
}
public class ExcelExporter
{
public static void ExportOrdersToExcel(HttpContext context, List<Model.pro_order_detail> orders)
{
// Using a memory stream to create Excel package
var package = new ExcelPackage();
// Add a worksheet
var worksheet = package.Workbook.Worksheets.Add("Orders");
// Add header row
worksheet.Cells["A1"].Value = "訂單編號";
worksheet.Cells["B1"].Value = "數量";
worksheet.Cells["C1"].Value = "牌位標題";
worksheet.Cells["D1"].Value = "陽上";
//worksheet.Cells["E1"].Value = "數量";
// Add data rows
int currentRow = 2;
foreach (var order in orders)
{
worksheet.Cells[$"A{currentRow}"].Value = order.order_no;//"AA2403220002"
worksheet.Cells[$"B{currentRow}"].Value = order.qty;//
worksheet.Cells[$"C{currentRow}"].Value = order.f_num_tablet;//牌位標題//"王俊傑"
worksheet.Cells[$"D{currentRow}"].Value = order.from_id_tablet;//陽上標題//"王吳淑英 王瑞萍 張鎧臣"
//worksheet.Cells[$"E{currentRow}"].Value = order.customize_data//自訂欄位//"$牌位主標題:\r\n$牌位副標題:\r\n$右標題:\r\n$祈福姓名:\r\n$祈福姓名2:\r\n$陽上姓名:\r\n$編號:"
currentRow++;
}
// Convert the Excel package to a byte array
byte[] bin = package.GetAsByteArray();
// Clear the response
context.Response.Clear();
// Set the response's content type to Excel
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Set the Content-Disposition header to prompt a download dialog
context.Response.AddHeader("content-disposition", "attachment; filename=Orders.xlsx");
// Write the byte array to the response's output stream
context.Response.OutputStream.Write(bin, 0, bin.Length);
// Flush the response and end it
context.Response.Flush();
context.Response.End();
}
}