using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using static Model.admin_log;
///
/// ShuWenController 的摘要描述
///
public class ShuWenController : ApiController
{
private Model.ezEntities _db = new Model.ezEntities();
public ShuWenController()
{
//
// TODO: 在這裡新增建構函式邏輯
//
}
[HttpGet]
[Route("api/shuwen/getshuwen")]
public IHttpActionResult GetShuWen(int? activitynum)
{
if (!activitynum.HasValue)
{
return BadRequest("請提供有效的 activitynum 參數。");
}
var shuwen = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault();
if(shuwen == null)
{
return Ok(new { message = "1", data = shuwen, latest = false });
}
var latest = _db.pro_order_detail.Where(b => b.pro_order.activity_num == activitynum)
.Where(c => c.UpdateTime > shuwen.UpdateTime).Count() > 0 ? false : true;
return Ok(new { message = "1", data = shuwen , latest= latest});
}
[HttpGet]
[Route("api/shuwen/StartGenerate")]
public IHttpActionResult CreateShuWen(int? activitynum)
{
if (!activitynum.HasValue)
{
return BadRequest("請提供有效的 activitynum 參數。");
}
var shuwen = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault();
if (shuwen == null)
{
var now = DateTime.Now;
shuwen = new Model.ShuWen();
shuwen.ActivityNum = activitynum.Value;
shuwen.CreateTime = now;
shuwen.UpdateTime = now;
shuwen.IsGenerating = true;
_db.ShuWen.Add(shuwen);
}
else if (shuwen.IsGenerating)
{
return Ok("任务正在处理中");
}
shuwen.IsGenerating = true;
_db.SaveChanges();
try
{
shuwen.ShuWenList = ProcessDesserts2(_db.pro_order_detail.Where(a => a.pro_order.activity_num == activitynum.Value).ToList());
}
catch (Exception ex)
{
shuwen.IsGenerating = false;
_db.SaveChanges();
return BadRequest("生成舒文失败:" + ex.Message);
}
shuwen.IsGenerating = false;
shuwen.UpdateTime = DateTime.Now;
_db.SaveChanges();
return Ok("已啟動生成任務");
}
public string ProcessDesserts2(List items)
{
var xiaozai = new List>>();
var chaodu = new List>>();
foreach (var item in items)
{
string json = item.f_num_tablet;
try
{
JObject obj = JObject.Parse(json);
var midItems = obj["mid_items"] as JArray;
var famNames = new List();
foreach (var mid in midItems ?? new JArray())
{
bool isShuWen = mid["IsShuWen"]?.Value() == true;
string famName = mid["fam_name"]?.ToString();
if (isShuWen && !string.IsNullOrWhiteSpace(famName))
{
famNames.Add(famName.Trim());
}
}
if (famNames.Count == 0) continue;
string orderNo = item.order_no;
var userObject = new
{
name = item.pro_order.follower.u_name,
};
if (item.actItem.subject.Contains("消"))
{
var existing = xiaozai.FirstOrDefault(d => d.ContainsKey(orderNo));
if (existing != null)
{
var data = (List)existing[orderNo]["biaoti"];
data.AddRange(famNames);
existing[orderNo]["biaoti"] = data.Distinct().ToList();
}
else
{
xiaozai.Add(new Dictionary>
{
{
orderNo,
new Dictionary
{
{ "user", userObject },
{ "biaoti", new List(famNames) }
}
}
});
}
}
else if (item.actItem.subject.Contains("超"))
{
var leftNames = new List();
if (obj["left_items"] != null && obj["left_items"].HasValues)
{
var leftItems = obj["left_items"] as JArray;
foreach (var left in leftItems ?? new JArray())
{
leftNames.Add(left["fam_name"]?.ToString());
}
}
else
{
continue;
}
if(leftNames.Count() == 0) continue;
var existing = chaodu.FirstOrDefault(d => d.ContainsKey(orderNo));
string leftFamName = string.Join(" ", leftNames).Trim();
if (existing != null)
{
var entryList = (List>)existing[orderNo]["entry"];
var existingYangshang = entryList.FirstOrDefault(e => IsSamePeople(e["yangshang"]?.ToString(), leftFamName));
if (existingYangshang != null)
{
var oldBiaoti = (List)existingYangshang["biaoti"];
oldBiaoti.AddRange(famNames);
existingYangshang["biaoti"] = oldBiaoti.Distinct().ToList();
}
else
{
entryList.Add(new Dictionary
{
{ "yangshang", leftFamName },
{ "biaoti", new List(famNames) }
});
}
}
else
{
chaodu.Add(new Dictionary>
{
{
orderNo,
new Dictionary
{
{ "user", userObject },
{
"entry",
new List>
{
new Dictionary
{
{ "yangshang", leftFamName },
{ "biaoti", new List(famNames) }
}
}
}
}
}
});
}
}
}
catch (JsonReaderException)
{
}
}
var result = new
{
xiaozai = xiaozai,
chaodu = chaodu
};
return JsonConvert.SerializeObject(result, Formatting.None);
}
[HttpGet]
[Route("api/shuwen/download")]
public HttpResponseMessage DownloadShuWenWord(int? activitynum)
{
try
{
var data = _db.ShuWen.Where(a => a.ActivityNum == activitynum).FirstOrDefault();
if (data == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "活動編號不能為空");
}
string json = data.ShuWenList;
string ActivityName = _db.activities.Where(a => a.num == data.ActivityNum).FirstOrDefault().subject;
if (json == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "疏文列表为空,无法生成 Word");
}
string fileName = $"疏文名單_{DateTime.Now:yyyyMMddHHmmss}.docx";
var stream = new MemoryStream();
GenerateShuWenWord_OpenXml(json, stream, ActivityName);
stream.Position = 0;
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
response.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return response;
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
public void GenerateShuWenWord_OpenXml(string json, Stream outputStream, string ActivityName ="")
{
JObject root = JObject.Parse(json);
using (var doc = WordprocessingDocument.Create(outputStream, WordprocessingDocumentType.Document, true))
{
var mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
var body = mainPart.Document.Body;
var sectionProps = new SectionProperties(
new PageSize() { Orient = PageOrientationValues.Landscape },
new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft }
);
mainPart.Document.Body.Append(sectionProps);
// === 處理 xiaozai ===
var xiaozai = root["xiaozai"] as JArray;
if (xiaozai != null)
{
foreach (var item in xiaozai.Children())
{
foreach (var prop in item.Properties())
{
string orderNo = prop.Name;
//var names = prop.Value.ToObject>();
var detail = prop.Value as JObject;
string username = detail?["user"]?["name"]?.ToString();
var biaotiList = detail?["biaoti"]?.ToObject>() ?? new List();
AddPageBreak(body);
var orderActItem = _db.pro_order_detail.Where(a => a.order_no == orderNo && a.actItem.act_bom.Where(b => b.package_num == null && b.item_num == a.actItem_num).Count() == 1).FirstOrDefault();
if(orderActItem != null)
{
username = orderActItem.actItem.subject;
}
body.Append(CreateHeading($"{ActivityName} {username} 消災祈福名單"));
/*foreach (var name in biaotiList)
{
body.Append(CreateParagraph(" " + name));
}*/
var combinedNames = string.Join(" ", biaotiList);
combinedNames = combinedNames.Replace(" ", " ");
body.Append(CreateParagraph(combinedNames));
}
}
}
// === 處理 chaodu ===
var chaodu = root["chaodu"] as JArray;
if (chaodu != null)
{
foreach (var item in chaodu.Children())
{
foreach (var prop in item.Properties())
{
string orderNo = prop.Name;
//var persons = prop.Value as JArray;
var detail = prop.Value as JObject;
string username = detail?["user"]?["name"]?.ToString();
var entries = detail?["entry"] as JArray;
var orderActItem = _db.pro_order_detail.Where(a => a.order_no == orderNo && a.actItem.act_bom.Where(b => b.package_num == null && b.item_num == a.actItem_num).Count() == 1).FirstOrDefault();
if (orderActItem != null)
{
username = orderActItem.actItem.subject;
}
AddPageBreak(body);
body.Append(CreateHeading($"{ActivityName} {username} 超薦名單"));
foreach (var person in entries)
{
string yangshang = person["yangshang"]?.ToString();
var biaotiList = person["biaoti"]?.ToObject>() ?? new List();
foreach (var b in biaotiList)
{
body.Append(CreateParagraph(" " + b));
}
body.Append(CreateParagraph("陽上報恩人:" + yangshang));
}
}
}
}
}
}
private Paragraph CreateHeading(string text)
{
return new Paragraph(
new Run(new RunProperties(
new FontSize() { Val = "50" }
), new Text(text))
)
{
ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Start },
new Bold(),
new SpacingBetweenLines() { After = "200" },
new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft }
)
};
}
private Paragraph CreateParagraph(string text)
{
return new Paragraph(
new Run(new RunProperties(
new FontSize() { Val = "40" }
),
new Text(text))
)
{
ParagraphProperties = new ParagraphProperties(
new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft }
)
}
;
}
private void AddPageBreak(Body body)
{
if (body.Elements().Any())
{
body.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })));
}
}
bool IsSamePeople(string a, string b)
{
var listA = a.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().OrderBy(x => x).ToList();
var listB = b.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().OrderBy(x => x).ToList();
return listA.SequenceEqual(listB);
}
[HttpPost]
[Route("api/shuwen/GetShuwenData")]
public IHttpActionResult GetShuwenData([FromBody] dynamic data)
{
var json = data;
var mode = (json.mode == null ? "" : (string)json.mode);
var num = (json.activity_num == null ? 0 : (int)json.activity_num);
var act = _db.activities.AsQueryable().Where(v => v.num == num).FirstOrDefault();
var query = _db.pro_order_detail.AsQueryable();
query = query.Where(x => (_db.act_bom.AsQueryable().Where(y => y.package_num == null).Select(y => y.item_num).ToList()).
Contains(x.actItem_num));
query = query.Where(x => (_db.pro_order.AsQueryable().
Where(w => w.activity_num == num).Select(w => w.order_no)).ToList().Contains(x.order_no));
//query = query.Include(x=>x.actItem).Where(x=>x.actItem.subject.StartsWith("消"));
//這些是功德主
var list = query.OrderByDescending(x => x.price).Select(x => new
{
x.num,
x.order_no,
x.actItem_num,
x.parent_num,
x.print_id,
x.f_num_tablet,
x.price,
subject = _db.actItems.Where(w => w.num == x.actItem_num).Select(w => w.subject).FirstOrDefault(),
childs = _db.pro_order_detail.
Where(z => z.order_no == x.order_no && z.parent_num == x.num).Select(z => new
{
z.num,
z.order_no,
z.actItem_num,
z.parent_num,
z.print_id,
z.f_num_tablet,
z.price,
subject = _db.actItems.Where(w => w.num == z.actItem_num).Select(w => w.subject).FirstOrDefault(),
}).ToList()
}).ToList();
var query1 = _db.pro_order_detail.AsQueryable();
query1 = query1.Where(x => !(_db.act_bom.AsQueryable().Where(y => y.package_num == null).Select(y => y.item_num).ToList()).
Contains(x.actItem_num));
query1 = query1.Where(x => x.parent_num == null);
query1 = query1.Where(x => (_db.pro_order.AsQueryable().
Where(w => w.activity_num == num).Select(w => w.order_no)).ToList().Contains(x.order_no));
query1 = query1.Include(x => x.actItem).Where(x => x.actItem.subject.StartsWith(mode == "消" ? "消" : "超"));
//這些是非功德主
var list1 = query1.Select(x => new
{
x.num,
x.order_no,
x.actItem_num,
x.parent_num,
x.print_id,
x.f_num_tablet,
x.price,
subject = _db.actItems.Where(w => w.num == x.actItem_num).Select(w => w.subject).FirstOrDefault(),
}).ToList();
//string filePath = "範例文件.docx";
string folderPath = HttpContext.Current.Server.MapPath("~/tempfile/");
// 確保資料夾存在
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// 2. 使用 GUID 命名防衝突
string fileName = Guid.NewGuid().ToString() + ".docx";
string fullPath = Path.Combine(folderPath, fileName);
if (mode == "消")
{
// 1. 建立 Word 文件
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document, true))
{
Body body = new Body();
var doc = GenerateDocument(wordDocument, body);
string preItemName = string.Empty;
foreach (var dd in list)
{
if (dd.childs.Count > 0)
{
if (preItemName != dd.subject)
{
body.Append(RenderParagraph(44, $"{act.subject}{dd.subject} 消災祈福名單", true, 0));
}
if (string.IsNullOrEmpty(preItemName))
{
preItemName = dd.subject;
}
List preItemTitle = new List();
foreach (var child in dd.childs)
{
if (!child.subject.StartsWith("消"))
{
continue;
}
//preItemTitle.Append(child)
JObject obj = JObject.Parse(child.f_num_tablet);
JArray arr = (JArray)obj["mid_items"];
foreach (var item in arr)
{
preItemTitle.Add((string)item["fam_name"]);
}
}
body.Append(RenderParagraph(44, $" {string.Join(" ", preItemTitle)}", false, 1134));
}
}
//ChangePage(body);
//if (list1.Count > 0)
//{
// Hashtable ht = new Hashtable();
// string preOrderNo = string.Empty;
// body.Append(RenderParagraph(44, $"{act.subject} 消災祈福名單", true));
// List preItemTitle = new List();
// foreach (var dd in list1)
// {
// if (preOrderNo != dd.order_no)
// {
// if (preItemTitle.Count > 0)
// {
// body.Append(RenderParagraph(44, $" {string.Join(" ", preItemTitle)}", false));
// }
// ht.Clear();
// preItemTitle.Clear();
// }
// JObject obj = JObject.Parse(dd.f_num_tablet);
// JArray arr = (JArray)obj["mid_items"];
// foreach (var item in arr)
// {
// if (ht.ContainsKey((string)item["fam_name"]))
// {
// continue;
// }
// if (string.Join(" ", preItemTitle).Length + ((string)item["fam_name"]).Length > 25)
// {
// body.Append(RenderParagraph(44, $" {string.Join(" ", preItemTitle)}", false));
// preItemTitle.Clear();
// }
// preItemTitle.Add((string)item["fam_name"]);
// ht.Add((string)item["fam_name"], (string)item["fam_name"]);
// }
// preOrderNo = dd.order_no;
// }
// if (preItemTitle.Count > 0)
// {
// body.Append(RenderParagraph(44, $" {string.Join(" ", preItemTitle)}", false));
// }
//}
SetStraight(body);
}
}
else if (mode == "超")
{
List shuwenList = new List();
Shuwen shuwen = new Shuwen();
string preOrderNo = string.Empty;
foreach (var dd in list)
{
if (preOrderNo != dd.order_no)
{
//if(!string.IsNullOrEmpty(shuwen.order_no)&&shuwen.mid_item.Count>0)
// shuwenList.Add(shuwen);
shuwen = new Shuwen();
shuwen.order_no = dd.order_no;
shuwen.subject = dd.subject;
shuwen.mid_item = new List();
}
if (dd.childs.Count > 0)
{
foreach (var item in dd.childs)
{
if (!item.subject.StartsWith("超"))
{
continue;
}
JObject obj = JObject.Parse(item.f_num_tablet);
JArray mid = (JArray)obj["mid_items"];
JArray left = (JArray)obj["left_items"];
List leftList = new List();
List midList = new List();
foreach (var o in mid)
{
midList.Add((string)o["fam_name"]);
}
foreach (var o in left)
{
leftList.Add((string)o["fam_name"]);
}
var wen = shuwenList.Where(z => z.alive == string.Join(" ", leftList) && z.order_no == dd.order_no).FirstOrDefault();
if (wen != null && wen.alive == string.Join(" ", leftList))
{
wen.mid_item.AddRange(midList);
shuwen = new Shuwen();
shuwen.order_no = dd.order_no;
shuwen.subject = dd.subject;
shuwen.mid_item = new List();
}
else
{
shuwen.alive = string.Join(" ", leftList);
shuwen.mid_item.AddRange(midList);
shuwenList.Add(shuwen);
}
}
//if (shuwen.mid_item.Count > 0)
//{
// shuwenList.Add(shuwen);
//}
}
preOrderNo = dd.order_no;
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document, true))
{
Body body = new Body();
var doc = GenerateDocument(wordDocument, body);
string preItem = string.Empty;
foreach (var shu in shuwenList)
{
if (preItem != shu.subject)
{
body.Append(RenderParagraph(44, $"{act.subject}{shu.subject} 超薦名單", true, 0));
}
body.Append(RenderParagraph(44, "佛力超薦", true, 0));
//foreach (var wen in shu.mid_item)
//{
// body.Append(RenderParagraph(44, $" {wen}", false));
//}
//這裡要改切段落
List para = new List();
foreach (var p in shu.mid_item)
{
if (string.Join(" ", para).Length + p.Length > 25)
{
body.Append(RenderParagraph(44, $" {string.Join(" ", para)}", false, 1134));
para.Clear();
}
para.Add(p.ToString());
}
if (para.Count > 0)
{
body.Append(RenderParagraph(44, $" {string.Join(" ", para)}", false, 1134));
para.Clear();
}
body.Append(RenderParagraph(44, $"陽上報恩人", true,0));
body.Append(RenderParagraph(44, $" {shu.alive}", false, 1134));
preItem = shu.subject;
}
SetStraight(body);
}
}
// 讀取檔案串流
var fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
// 建立原始的 HttpResponseMessage
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(fileStream)
};
// 設定 Word 檔案的 Content-Type 與下載檔名
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"{act.subject}_{mode}.docx"
};
// 使用 ResponseMessage 方法將 HttpResponseMessage 轉為 IHttpActionResult
return ResponseMessage(response);
//return Ok(new { result = "Y", data = new { list = list, list1 = list1 } });
}
public void ChangePage(Body body)
{
Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00A56886", RsidRunAdditionDefault = "00D919D0" };
Run pageBreakRun = new Run();
pageBreakRun.Append(new Break() { Type = BreakValues.Page }); // 指定 Break 類型為 Page (換頁)
paragraph1.Append(pageBreakRun);
body.Append(paragraph1);
}
public WordprocessingDocument GenerateDocument(WordprocessingDocument document1, Body body)
{
MainDocumentPart mainPart = document1.AddMainDocumentPart();
mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
mainPart.Document.AppendChild(body);
return document1;
}
public void SetStraight(Body body)
{
SectionProperties sectionProperties1 = new SectionProperties() { RsidR = "00A56886", RsidSect = "00D919D0" };
PageSize pageSize1 = new PageSize() { Width = 16838U, Height = 11906U, Orient = PageOrientationValues.Landscape };
PageMargin pageMargin1 = new PageMargin() { Top = 1440, Right = 1440U, Bottom = 1440, Left = 1440U, Header = 720U, Footer = 720U, Gutter = 0U };
Columns columns1 = new Columns() { Space = "720" };
TextDirection textDirection3 = new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft };
DocGrid docGrid1 = new DocGrid() { LinePitch = 326 };
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(textDirection3);
sectionProperties1.Append(docGrid1);
body.Append(sectionProperties1);
}
public Paragraph RenderParagraph(int fontSize, string content, bool isBold,int indentSize)
{
Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "00A56886", RsidRunAdditionDefault = "00D919D0" };
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
TextDirection textDirection2 = new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft };
// 2. 建立縮排物件
Indentation indent = new Indentation();
// --- 請依需求選擇以下一種縮排方式設定 ---
// 懸首縮排 (Hanging): 第一行不動,其餘行縮排。 (1公分約為 567 dxa)
indent.Left = $"{ indentSize }"; // 整體左縮排量
indent.Hanging = $"{indentSize}";
//indent.FirstLine = "1134";
paragraphProperties2.Append(indent);
paragraphProperties2.Append(textDirection2);
Run run2 = new Run();
RunProperties runProperties2 = new RunProperties();
RunFonts runFonts2 = new RunFonts() { Hint = FontTypeHintValues.EastAsia, Ascii = "標楷體", EastAsia = "標楷體" };
FontSize fontSize2 = new FontSize() { Val = $"{fontSize}" };
runProperties2.Append(runFonts2);
runProperties2.Append(fontSize2);
if (isBold)
{
runProperties2.Append(new Bold());
}
Text text2 = new Text();
text2.Space = SpaceProcessingModeValues.Preserve;
text2.Text = $"{content}";
run2.Append(runProperties2);
run2.Append(text2);
paragraph2.Append(paragraphProperties2);
paragraph2.Append(run2);
return paragraph2;
}
[HttpPost]
[Route("api/shuwen/PrintItemReport")]
public IHttpActionResult PrintItemReport([FromBody] dynamic data)
{
var json = data;
var mode = (json.mode == null ? "" : (string)json.mode);
var num = (json.activity_num == null ? 0 : (int)json.activity_num);
var actItems = (json.actItems == null ? new JArray() : (JArray)json.actItems);
List primitiveIds = actItems.ToObject>();
var qry=_db.pro_order_detail.AsQueryable();
qry = qry.Where(x=>(_db.pro_order.Where(y=>y.activity_num==num).Select(y=>y.order_no).ToList().
Contains(x.order_no))).Where(x=> primitiveIds.Contains(x.actItem_num));
var list = qry.Select(x => new
{
x.qty,x.price,
name=_db.pro_order.Where(y=>y.order_no==x.order_no).Select(y=>new
{
u_name=_db.followers.Where(z=>z.num==y.f_num).Select(z=>z.u_name).FirstOrDefault()
}).FirstOrDefault()
}).ToList();
//string filePath = "範例文件.docx";
string folderPath = HttpContext.Current.Server.MapPath("~/tempfile/");
// 確保資料夾存在
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// 2. 使用 GUID 命名防衝突
string fileName = Guid.NewGuid().ToString() + ".docx";
string fullPath = Path.Combine(folderPath, fileName);
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document, true))
{
Body body = new Body();
var doc = GenerateDocument(wordDocument, body);
// 1. 建立表格物件
Table table = new Table();
// 2. 設定表格邊框樣式 (選擇性)
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder { Val = BorderValues.Single, Size = 4 },
new BottomBorder { Val = BorderValues.Single, Size = 4 },
new LeftBorder { Val = BorderValues.Single, Size = 4 },
new RightBorder { Val = BorderValues.Single, Size = 4 },
new InsideHorizontalBorder { Val = BorderValues.Single, Size = 4 }, // 修正這行
new InsideVerticalBorder { Val = BorderValues.Single, Size = 4 } // 修正這行
)
);
TableWidth tableWidthPercent = new TableWidth()
{
Width = "5000",
Type = TableWidthUnitValues.Pct
};
tblProp.AppendChild(tableWidthPercent);
table.AppendChild(tblProp);
// 3. 建立第一列 (標頭列)
TableRow row1 = new TableRow();
TableCell cell1 = new TableCell(RenderParagraph(44, "姓名", false,0));
TableCell cell2 = new TableCell(RenderParagraph(44, "姓名", false, 0));
row1.Append(cell1, cell2);
table.Append(row1);
TableRow row2 = new TableRow();
int i = 0;
var newList=list.GroupBy(x => x.name).Select(g => new
{
name=g.Key,qty=g.Sum(s=>s.qty),price=g.FirstOrDefault().price
}).ToList();
foreach (var d in newList) {
// 4. 建立第二列 (資料列)
TableCell cell3 = new TableCell(RenderParagraph(44, d.name.u_name, false, 0));
if (i == 0)
{
row2 = new TableRow();
}
row2.Append(cell3);
if (i == 1)
{
table.Append(row2);
}
if (i == 0) {
i = 1;
}
else
{
i = 0;
}
}
if (newList.Count%2!=0)
{
TableCell cell3 = new TableCell(RenderParagraph(44, "", false, 0));
row2.Append(cell3);
table.Append(row2);
}
body.Append(table);
// 將表格加入到文件主體中
//mainPart.Document.Body.Append(table);
//mainPart.Document.Save();
}
// 讀取檔案串流
var fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
// 建立原始的 HttpResponseMessage
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(fileStream)
};
// 設定 Word 檔案的 Content-Type 與下載檔名
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"{mode}.docx"
};
// 使用 ResponseMessage 方法將 HttpResponseMessage 轉為 IHttpActionResult
return ResponseMessage(response);
}
}
public class Shuwen
{
public Shuwen() { }
public string order_no { get; set; }
public List mid_item { get; set; }
public string alive { get; set; }
public string subject { get; set; }
}