以下C#程式碼可用於生成Excel類型的報告:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using GemBox.Spreadsheet;
using SharpCompress.Compressors.ADC;
namespace ProSmart.ReportingServices
{
internal class ExcelReportGenerator
{
public SaveOptions _saveOptions { get; set; } = SaveOptions.XlsxDefault;
private ExcelFile _workbook;
public ExcelReportGenerator(Stream template)
{
_workbook = ExcelFile.Load(template, LoadOptions.XlsxDefault);
FontSettings.FontsBaseDirectory = "Fonts";
FontSettings.FontsBaseResourceLocation = "/Fonts/";
_workbook.Styles[BuiltInCellStyleName.Normal].Font.Name = "NotoSansHK";
}
code Copy code
public ExcelReportGenerator()
{
_workbook = new ExcelFile();
FontSettings.FontsBaseDirectory = "Fonts";
FontSettings.FontsBaseResourceLocation = "/Fonts/";
var workSheet = _workbook.Worksheets.Add("Raw Data");
workSheet.Parent.Styles.Normal.Font.Name = "NotoSansHK";
}
public ExcelReportGenerator(string fileType)
{
_workbook = new ExcelFile();
FontSettings.FontsBaseDirectory = "Fonts";
FontSettings.FontsBaseResourceLocation = "/Fonts/";
var workSheet = _workbook.Worksheets.Add("Raw Data");
workSheet.Parent.Styles.Normal.Font.Name = "NotoSansHK";
if (fileType == "pdf")
_saveOptions = SaveOptions.PdfDefault;
else if(fileType == "xlsx")
_saveOptions = SaveOptions.XlsxDefault;
}
public void Save(MemoryStream outputStream)
{
_workbook.Save(outputStream, _saveOptions);
outputStream.Position = 0;
}
public void CreateHeader(List<string> headers, string sheetName = "Raw Data")
{
var rawDataSheet = _workbook.Worksheets[sheetName];
// Write the headers to the first row
for (int i = 0; i < headers.Count; i++)
{
rawDataSheet.Cells[0, i].Value = headers[i]; // Row 0, Column i
}
// Auto fit requires Drawing dll. This dll requires gdi+ which does not support in non windows after .net 6.
//for (int j = 0; j < headers.Count; j++)
//{
// rawDataSheet.Columns[j].AutoFit();
//}
}
public void FillTable(List<List<string>> data, List<Type> colTypes, string sheetName = "Raw Data")
{
var rawDataSheet = _workbook.Worksheets[sheetName];
rawDataSheet.PrintOptions.Portrait = false;
rawDataSheet.PrintOptions.FitWorksheetWidthToPages = 1;
var lastRow = rawDataSheet.Rows.Count;
if (lastRow > 2)
{
rawDataSheet.Cells.GetSubrange("A2", $"Z{lastRow}").Clear(ClearOptions.Content);
}
for (int rowIndex = 0; rowIndex < data.Count; rowIndex++)
{
var row = data[rowIndex];
for (int colIndex = 0; colIndex < row.Count; colIndex++)
{
Type targetType = colTypes[colIndex];
if (row[colIndex] != null)
{
if (!string.IsNullOrEmpty(row[colIndex]))
{
var valObj = Convert.ChangeType(row[colIndex], targetType);
rawDataSheet.Cells[rowIndex + 1, colIndex].Value = valObj;
}
}
}
}
}
}
}
我希望將以下程式碼改寫成分批將數據寫入至同一Excel中以減少記憶體的資源佔用,而非將所有數據預載於RAM中:
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection("ProSupplierMasterInfo");
_helper = new ReportingServicesDbTransactionHelper(_dbContext);
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
var entities = new List();
code Copy code
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
entities.Add(BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc));
}
}
var xlsgen = new ExcelReportGenerator();
if (entities != null)
{
FillExcel(xlsgen, entities);
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMaster.xlsx");
return proFileDto;
}
}
Show full message · 133 lines Assistant2025-07-09 07:44 UTC Copy response
你目前的邏輯是先將從MongoDB交易取得的所有資料全部讀入到一個List<ProSupplierMasterInfoEntityDto>(entities)中,再一次性把所有資料寫入Excel。這樣在面對大量資料時,會導致記憶體消耗過高。
優化思路是:
「邊讀邊寫」(streaming/memory-friendly),也就是每讀一批資料,就立刻寫入Excel,避免先暫存全部資料在記憶體。GemBox.Spreadsheet 支持動態寫入單元格。只要正確維護目前寫入的行數指標即可。
改寫範例
csharp Copy code
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection<BsonDocument>("ProSupplierMasterInfo");
_helper = new ReportingServicesDbTransactionHelper(_dbContext);
var xlsgen = new ExcelReportGenerator();
// 先建立Excel的表頭
var headers = new List<string> { "欄位1", "欄位2", "欄位3", /*...*/ };
xlsgen.CreateHeader(headers);
int currentRow = 1; // Excel行號,索引從0開始,0是標題
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
// 將Batch逐筆寫入Excel
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
// 把單筆資料轉成string list(或是對應欄位list,可依需求調整)
var rowData = new List<string>
{
entity.Field1?.ToString(),
entity.Field2?.ToString(),
entity.Field3?.ToString(),
// ...
};
// 利用 FillTable 分批寫入,或自行直接呼叫 _workbook.Cells
// 因為 FillTable 是寫整批資料,這裡改成直接用 ExcelReportGenerator 的儲存格操作模式
var sheet = xlsgen.GetWorksheet("Raw Data"); // 需要對ExcelReportGenerator加上取得Worksheet的方法
for (int col = 0; col < rowData.Count; col++)
{
sheet.Cells[currentRow, col].Value = rowData[col];
}
currentRow++;
}
}
}
// 寫入完成後儲存
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMaster.xlsx");
return proFileDto;
}
我忘記提供以下程式碼:
private void FillExcel(ExcelReportGenerator xlsgen, List entities)
{
var colFields = new List
{
"Supplier Name",
code Copy code
"FMS Supplier Number",
"System Supplier Number",
"Supplier Classification",
"Supplier Type",
"Overall Performance Score",
"Supplier Category",
"Location",
"BR Expiry Date",
"Date of First Submission for Approval(Pre-registration)",
"Date of Approval(Pre-registration)",
"Date of First Submission for Approval(Full registration)",
"Date of Approval(Full registration)",
};
xlsgen.CreateHeader(colFields);
var columnTypes = new List<Type> { };
foreach (var tableCol in colFields)
{
columnTypes.Add(typeof(string));
}
var table = new List<List<string>>();
foreach (var entity in entities)
{
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity);
table.AddRange(curEntityData);
}
}
xlsgen.FillTable(table, columnTypes);
}
請檢閱再次生成
Show full message · 47 lines Assistant2025-07-09 07:46 UTC Copy response
謝謝補充你原本的 FillExcel 方法。它的邏輯是:
建立欄位名稱(Headers)
產生欄位型別全為 string
透過 ConstructTableFromData 把每筆 Entity 轉成多列的 List<List<string>> 表格資料
呼叫 FillTable 一次性寫入全部資料
你的需求
你想分批寫入excel,避免所有資料先累積於記憶體(table list會爆掉)
改寫策略
保持欄位 Header 用 CreateHeader,只呼叫一次
因為每筆 Entity 可能會轉成多列(多筆row),無法用原本的 FillTable 一次性寫入整個List<List>,
改為:每取到一筆 Entity,馬上轉成多列 curEntityData,接著呼叫填資料的方法分批寫入
由於目前 ExcelReportGenerator 沒有提供「單筆多列寫入」的API,我們自己直接操作 Worksheet.Cells 寫入資料即可
詳細重構範例碼
csharp Copy code
// 在ExcelReportGenerator中新增取得Worksheet方法
public ExcelWorksheet GetWorksheet(string sheetName = "Raw Data")
{
return _workbook.Worksheets[sheetName];
}
csharp Copy code
// 新增一組方法批次寫入Excel資料
public void WriteRows(int startRowIndex, List<List<string>> rows, List<Type> columnTypes, string sheetName = "Raw Data")
{
var sheet = GetWorksheet(sheetName);
for (int i = 0; i < rows.Count; i++)
{
var row = rows[i];
for (int colIndex = 0; colIndex < row.Count; colIndex++)
{
var stringVal = row[colIndex];
Type tgtType = columnTypes[colIndex];
if (!string.IsNullOrEmpty(stringVal))
{
// 直接Convert給Cell.Value
var valObj = Convert.ChangeType(stringVal, tgtType);
sheet.Cells[startRowIndex + i, colIndex].Value = valObj;
}
}
}
}
調整後的呼叫端邏輯範例:分批讀mongo並寫入
請按相同邏輯,改寫以下程式碼:
private void FillExcel(ExcelReportGenerator xlsgen, List entities)
{
var columnTypes = new List { };
var supplierFields = new List
{
"Supplier Type",
"Supplier Status",
"Supplier Name",
"FMS Supplier Number",
"EPRO Supplier Number",
"Business Registration Number",
"Business Registration Number Expiry Date",
"Business Registration Region",
"Company Address",
"Contact Person Name",
"Contact Person Position",
"Contact Email",
"Contact Phone Number (Office)",
"Fax Number",
"Procurement Category 1",
"Procurement Category 2",
"Procurement Category 3",
"Pre-Registration Invited by Buyer Date",
"Buyer and Position for Pre-Registration Invitation",
"Pre-Registration Submitted by Supplier Date",
"Pre-Registration Checked by Buyer Date",
"Full Registration Invited by Buyer Date",
"Buyer and Position for Full Registration Invitation",
"Full Registration Submitted by Supplier Date",
"Full Registration Checked by Buyer Date",
//"Full Registration Approved in FMS Date",
"Suspension Start Date",
"Suspension End Date",
"Suspension Remarks",
"Overall Performance Score",
"Termination Start Date",
"Termination Remarks"
};
xlsgen.CreateHeader(supplierFields);
code Copy code
foreach (var tableCol in supplierFields)
{
columnTypes.Add(typeof(string));
}
var table = new List<List<string>>();
foreach (var entity in entities)
{
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity);
table.AddRange(curEntityData);
}
}
xlsgen.FillTable(table, columnTypes);
}
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection("ProSupplierMasterInfo");
dbHelper = new ReportingServicesDbTransactionHelper(_dbContext);
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
var entities = new List();
code Copy code
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
entities.Add(BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc));
}
}
var xlsgen = new ExcelReportGenerator();
if (entities != null)
{
FillExcel(xlsgen, entities);
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMaster.xlsx");
return proFileDto;
}
Show full message · 87 lines Assistant2025-07-09 07:50 UTC Copy response
依你的需求,以「分批讀mongo資料並即時寫入Excel」的邏輯,下面示範改寫版程式碼。
同樣是避免先把全部資料累積於記憶體,改成邊讀邊寫。
Step 1:調整ExcelReportGenerator加上的方法
csharp Copy code
// 取得 Worksheet 實體
public ExcelWorksheet GetWorksheet(string sheetName = "Raw Data")
{
return _workbook.Worksheets[sheetName];
}
// 一次寫入多列資料(支援Convert類型)
public void WriteRows(int startRowIndex, List<List<string>> rows, List<Type> columnTypes, string sheetName = "Raw Data")
{
var sheet = GetWorksheet(sheetName);
for (int i = 0; i < rows.Count; i++)
{
var row = rows[i];
for (int colIndex = 0; colIndex < row.Count; colIndex++)
{
var stringVal = row[colIndex];
Type tgtType = columnTypes[colIndex];
if (!string.IsNullOrEmpty(stringVal))
{
var valObj = Convert.ChangeType(stringVal, tgtType);
sheet.Cells[startRowIndex + i, colIndex].Value = valObj;
}
}
}
}
Step 2:改寫FillExcel改名為FillExcelBatch(或直接在呼叫端自行處理)
csharp Copy code
private void FillExcelBatch(ExcelReportGenerator xlsgen, IEnumerator<ProSupplierMasterInfoEntityDto> entityEnumerator, List<string> supplierFields)
{
var columnTypes = supplierFields.Select(_ => typeof(string)).ToList();
// 先建立欄位標題
xlsgen.CreateHeader(supplierFields);
int currentRow = 1;
while (entityEnumerator.MoveNext())
{
var entity = entityEnumerator.Current;
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity);
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
以下程式碼是最新的版本,已解決Out of Memory問題,但出現Timeout問題,有辦法加快速度嗎?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Spreadsheet;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using ProSmart.Core;
using ProSmart.Dtos.EntityDto.AuthService;
using ProSmart.Dtos.EntityDto.ConfigurationService;
using ProSmart.Dtos.EntityDto.SupplierService;
using ProSmart.Dtos.EntityDto.TenderingService;
using ProSmart.Dtos.Enumurable.SupplierServices;
using ProSmart.Dtos.EventDtos.ActionEvent.FileServices;
using ProSmart.Dtos.EventDtos.QueryEvent.ReportingService;
using ProSmart.ReportingServices.Handlers;
using ProSmart.ReportingServices.Helper;
using ProSmart.ReportingServices.Modules;
namespace ProSmart.ReportingServices.Reports
{
internal class SupplierMasterReport : ReportBase
{
private ReportingServicesDbTransactionHelper dbHelper;
public SupplierMasterReport(FileHandler fileHandler, BucketPathHandler bucketPathHandler, ReportingServicesDbContext dbContext, GenerateReportQueryDto dto, string userId)
: base(fileHandler, bucketPathHandler, dbContext, dto, userId)
{
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Show full message · 328 lines Assistant2025-07-09 07:55 UTC Copy response
你現有邏輯的「Timeout 問題」很可能來自以下兩個瓶頸:
MongoDB I/O 與資料讀取速度慢
ConstructTableFromData 裡大量 DB 查詢導致延遲
特別是你在 ConstructTableFromData 裡,每一筆 Entity 都調用 dbHelper.GetReadOnlyCollectionQuery<XXX>().FirstOrDefault(...) 查資料(例如取得 Suspend、Termination、Category、Inviter 等),這是針對每筆Entity都去「同步查DB」,非常耗時。
加快速度的優化方向
1️⃣ 把重覆查詢改為批次一次性查出並快取(cache)
問題例子
csharp Copy code
var supplierSuspendData = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>()
.LastOrDefault(item => item.SupplierId == entity.Id);
這樣每一筆 entity 跑時都查一次資料庫。
解決方案
一次將所有 ProSupplierSuspendEntityDto 讀出存成 Dictionary<SupplierId, ProSupplierSuspendEntityDto>
一次將所有 ProSupplierTerminationEntityDto 讀出存成 Dictionary<SupplierId, ProSupplierTerminationEntityDto>
一次將所有 ProInviteUserEntityDto 讀出存成 Dictionary<UserId, ProInviteUserEntityDto>
一次將所有 ProCategoryEntityDto 讀出存成 Dictionary<CategoryId, ProCategoryEntityDto>
如此後續查詢就不用每筆entity都Hit DB,改純粹記憶體Dictionary查找,速度可大幅提升
示範如何一次快取(以 SuspendData 為例)
csharp Copy code
// 先取得所有需要的資料,並建立索引
var suspendDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>().ToList();
var suspendDataDict = suspendDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var terminationDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierTerminationEntityDto>().ToList();
var terminationDataDict = terminationDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var inviteUserList = dbHelper.GetReadOnlyCollectionQuery<ProInviteUserEntityDto>().ToList();
var inviteUserDict = inviteUserList.GroupBy(x => x.UserId)
.ToDictionary(g => g.Key, g => g.FirstOrDefault());
var categoryList = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToList();
var categoryDict = categoryList.ToDictionary(x => x.Id);
取得所有關聯資料快取的部分假若數據量大會否同樣佔用很多系統資源?
Assistant2025-07-09 07:58 UTC Copy response
你問「取得所有關聯資料快取的部分,若數據量大會否同樣佔用很多系統資源?」這是非常合理且重要的疑慮。
以下是詳細分析與建議:
1. 快取所有關聯資料會占用多少資源?
若快取資料量很大(可能數十萬筆甚至更多) ,一次將全部關聯資料載入記憶體(ToList()),確實會消耗大量RAM,也可能導致GC負擔變重。
這種做法適合關聯資料集「相對較小」或「有限範圍」的情況。
2. 如何判斷是否可行?
先評估關聯資料數量:
例如 ProSupplierSuspendEntityDto 數量是10000以下,通常系統可以輕鬆負擔。
超過10萬筆時就需要特別注意。
3. 若資料量很大,建議改用以下策略:
(A) 分批查詢快取(Batch Cache)
將主查詢的IDs 先取得,在此基礎上篩選並分批查詢相關關聯資料。
範例流程:
csharp Copy code
// 1. 查mongodb索引,取得符合條件entity的ID集合(先只查ID)
var ids = new List<Guid>();
using(var cursor = await collection.Find(filter).Project(Builders<BsonDocument>.Projection.Include("_id")).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
ids.AddRange(cursor.Current.Select(doc => doc["_id"].AsGuid));
}
}
// 2. 根據ids批次查詢關聯資料,例如一次查幾千筆
var batchSize = 1000;
var suspendDataDict = new Dictionary<Guid, ProSupplierSuspendEntityDto>();
var terminationDataDict = new Dictionary<Guid, ProSupplierTerminationEntityDto>();
var inviteUserDict = new Dictionary<Guid, ProInviteUserEntityDto>();
var categoryDict = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToDictionary(x => x.Id); // 類別一般數量較少
for(int i=0; i < ids.Count; i += batchSize)
{
var batchIds = ids.Skip(i).Take(batchSize).ToList();
var suspends = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>()
.Where(x => batchIds.Contains(x.SupplierId))
.ToList();
foreach(var item in suspends)
suspendDataDict[item.SupplierId] = item; // 依需要保留最新或合適的
var terminations = dbHelper.GetReadOnlyCollectionQuery<ProSupplierTerminationEntityDto>()
.Where(x => batchIds.Contains(x.SupplierId))
.ToList();
foreach (var item in terminations)
terminationDataDict[item.SupplierId] = item;
var invites = dbHelper.GetReadOnlyCollectionQuery<ProInviteUserEntityDto>()
.Where(x => batchIds.Contains(x.UserId))
.ToList();
foreach (var item in invites)
inviteUserDict[item.UserId] = item;
}
請提供categories 改用快取字典查詢的更改
Assistant2025-07-09 08:06 UTC Copy response
你先前的程式碼裡 ConstructTableFromData 是這樣查 Category:
csharp Copy code
ProCategoryEntityDto catData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == proCat.CategoryId);
// ...重複多次查詢不同 CategoryId
這裡的瓶頸在於每次都去DB查詢。
改成用快取字典查詢的步驟
1. 在取得報告前,先快取所有 Categories 並以 Id 為 key 建立字典
csharp Copy code
// 快取所有 Category,字典 key 是 CategoryId,value 是 Category 物件
var categoryList = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToList();
var categoryDict = categoryList.ToDictionary(x => x.Id);
2. 在 ConstructTableFromData 中加入 categoryDict 參數
請重新檢視以下程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Spreadsheet;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using ProSmart.Core;
using ProSmart.Dtos.EntityDto.AuthService;
using ProSmart.Dtos.EntityDto.ConfigurationService;
using ProSmart.Dtos.EntityDto.SupplierService;
using ProSmart.Dtos.EntityDto.TenderingService;
using ProSmart.Dtos.Enumurable.SupplierServices;
using ProSmart.Dtos.EventDtos.ActionEvent.FileServices;
using ProSmart.Dtos.EventDtos.QueryEvent.ReportingService;
using ProSmart.ReportingServices.Handlers;
using ProSmart.ReportingServices.Helper;
using ProSmart.ReportingServices.Modules;
namespace ProSmart.ReportingServices.Reports
{
internal class SupplierMasterReport : ReportBase
{
private ReportingServicesDbTransactionHelper dbHelper;
public SupplierMasterReport(FileHandler fileHandler, BucketPathHandler bucketPathHandler, ReportingServicesDbContext dbContext, GenerateReportQueryDto dto, string userId)
: base(fileHandler, bucketPathHandler, dbContext, dto, userId)
{
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Show full message · 348 lines Assistant2025-07-09 08:11 UTC Copy response
你目前ConstructTableFromData中的Category相關部分,仍在對每筆Category和父Category做多次dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(...)查詢,這樣重覆查資料庫會影響效率。
既然你已經快取所有Category並建立字典:
csharp Copy code
var categoryDict = categoryList.ToDictionary(x => x.Id);
以下是「改用此快取字典查詢」的修改版Category處理程式碼,直接取代ConstructTableFromData內原先有關Categoryนั้น段:
csharp Copy code
var categories = new List<ProCategoryEntityDto>();
string cat1_text = "";
string cat2_text = "";
string cat3_text = "";
if (entity.Categories != null && entity.Categories.Count > 0)
{
// 先取得Primary Category
ProSupplierCategory primaryCat = entity.Categories.FirstOrDefault(c => c.IsPrimary == true);
if (primaryCat != null && categoryDict.TryGetValue(primaryCat.CategoryId, out var primaryCatData))
{
categories.Add(primaryCatData);
}
// 依照順序加入最多2個非Primary Category,總共最多3個
foreach (var cat in entity.Categories)
{
if (categories.Count == 3)
break;
if (!cat.IsPrimary && categoryDict.TryGetValue(cat.CategoryId, out var catData))
{
categories.Add(catData);
}
}
}
// 定義輔助方法回傳帶父分類的文字描述
string FormatCategoryText(ProCategoryEntityDto cat)
{
if (cat == null)
return "";
string parentText = "";
if (cat.ParentId.HasValue && categoryDict.TryGetValue(cat.ParentId.Value, out var parentCat))
{
parentText = string.IsNullOrEmpty(parentCat.Description?.Eng) ? "" : parentCat.Description.Eng + " > ";
}
return parentText + (cat.Description?.Eng ?? "");
}
// 分別取得前三個類別文字
if (categories.Count > 0)
cat1_text = FormatCategoryText(categories[0]);
if (categories.Count > 1)
cat2_text = FormatCategoryText(categories[1]);
if (categories.Count > 2)
cat3_text = FormatCategoryText(categories[2]);
其他說明:
透過categoryDict.TryGetValue(...)直接從快取字典找Category及父Category,避免同步DB查詢
不改變功能,只是把查詢由DB改成字典查詢,大幅提升速度與效能
把此段程式碼放置於ConstructTableFromData內,替代原本Category查詢那部分即可。
如果需要完整範例或其他部份也需要改寫,請告訴我!
請整合你改寫Category查詢的部分至以下程式碼:
if(entity.Categories != null)
{
// Get the Primary Category First
if(entity.Categories.Count > 0)
{
ProSupplierCategory proCat = entity.Categories.FirstOrDefault(item => item.IsPrimary == true);
if (proCat != null)
{
ProCategoryEntityDto catData = _helper.GetReadOnlyCollectionQuery().FirstOrDefault(item => item.Id == proCat.CategoryId);
if (catData?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = _helper.GetReadOnlyCollectionQuery().FirstOrDefault(item => item.Id == catData.ParentId);
supplierCat += ParentCatData?.Description?.Eng + " > ";
}
supplierCat += catData?.Description?.Eng;
}
code Copy code
foreach (var cat in entity.Categories)
{
if (cat.IsPrimary != true)
{
ProCategoryEntityDto catData = _helper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == cat.CategoryId);
if (catData?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = _helper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == catData.ParentId);
supplierCat += ParentCatData?.Description?.Eng + " > ";
}
supplierCat += catData?.Description?.Eng;
}
}
}
}
假設已完成快取字典的讀取
Assistant2025-07-09 08:24 UTC Copy response
以下將你原本依序查詢資料庫的Category程式碼,改為利用預先快取完成的字典categoryDict查詢,並整合為更清晰的寫法。請用此程式碼取代原本判斷entity.Categories != null那段:
csharp Copy code
if (entity.Categories != null && entity.Categories.Count > 0)
{
// 定義輔助方法格式化單一Category文字(含父分類)
string FormatCategoryWithParent(ProCategoryEntityDto cat)
{
if (cat == null) return "";
string parentText = "";
if (cat.ParentId.HasValue && categoryDict.TryGetValue(cat.ParentId.Value, out var parentCat))
{
parentText = string.IsNullOrEmpty(parentCat.Description?.Eng) ? "" : parentCat.Description.Eng + " > ";
}
return parentText + (cat.Description?.Eng ?? "");
}
// 先取得 Primary Category
ProSupplierCategory primaryCat = entity.Categories.FirstOrDefault(c => c.IsPrimary == true);
if (primaryCat != null && categoryDict.TryGetValue(primaryCat.CategoryId, out var primaryCatData))
{
supplierCat += FormatCategoryWithParent(primaryCatData);
}
// 取得其他非 Primary Categories,依序加入字串
foreach (var cat in entity.Categories)
{
if (!cat.IsPrimary)
{
if (categoryDict.TryGetValue(cat.CategoryId, out var catData))
{
supplierCat += FormatCategoryWithParent(catData);
}
}
}
}
重點說明:
以categoryDict.TryGetValue()取代資料庫同步查詢
每次格式化Category文字時,會嘗試把父分類文字也串入
先處理主分類,再依序處理非主分類,維持原邏輯
supplierCat為外層字串變數,且只管拼接文字
如果 supplierCat 用在輸出或表格中,記得先初始化為空字串""。
此寫法已能大幅改善讀取效能,降低DB查詢成本。
Copy first response
Not yet included in a published release.
調整 ExcelReportGenerator 以支援取得 Worksheet 在ExcelReportGenerator內新增一個方法:
csharp Copy code
public ExcelWorksheet GetWorksheet(string sheetName = "Raw Data")
{
return _workbook.Worksheets[sheetName];
}
重點解析
var entities = new List<ProSupplierMasterInfoEntityDto>(); 不再累積所有資料。
寫入Excel的row索引currentRow是邊讀邊寫時的關鍵。
不直接使用 FillTable 因為此方法是寫整個List<List<string>>的表格資料。
直接操作Excel單元格 sheet.Cells[row, col].Value寫入逐行資料。
這樣程式會有效減少一次性佔用大量RAM的問題。
小技巧 若 ProSupplierMasterInfoEntityDto 欄位很多,建議寫一個 helper 函式,將單筆轉成 string list,方便彈性寫入。
如果有需要,我也可以示範更完善的分批寫入範例與檔案流儲存範例,請告訴我。
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection<BsonDocument>("ProSupplierMasterInfo");
_helper = new ReportingServicesDbTransactionHelper(_dbContext);
var xlsgen = new ExcelReportGenerator();
// 建立欄位
var colFields = new List<string>
{
"Supplier Name",
"FMS Supplier Number",
"System Supplier Number",
"Supplier Classification",
"Supplier Type",
"Overall Performance Score",
"Supplier Category",
"Location",
"BR Expiry Date",
"Date of First Submission for Approval(Pre-registration)",
"Date of Approval(Pre-registration)",
"Date of First Submission for Approval(Full registration)",
"Date of Approval(Full registration)",
};
xlsgen.CreateHeader(colFields);
var columnTypes = colFields.Select(x => typeof(string)).ToList();
int currentRow = 1; // 跳過標題留給第一列
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
if (entity != null)
{
// 立即將該entity轉成多筆row List<List<string>>
var curEntityData = ConstructTableFromData(entity);
// 分批寫入Excel
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMaster.xlsx");
return proFileDto;
}
補充說明
ConstructTableFromData回傳是List<List<string>>,每筆Entity可能變多列,
WriteRows支援寫入任何行數和欄數的資料集合,並轉換型別
整個流程不會累積所有資料至List,而是「單筆轉換、立即寫入」
需要補上GetWorksheet與WriteRows到ExcelReportGenerator內
FillTable的單次批次使用在這個分批寫入情境已無法直接用,改寫成如上即可
如有需要,我可以協助你調整ExcelReportGenerator完整定義,或是示範ConstructTableFromData的結構範例。你可隨時告知。
Step 3:主流程改寫,邊讀mongo邊寫Excel: csharp Copy code
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection<BsonDocument>("ProSupplierMasterInfo");
dbHelper = new ReportingServicesDbTransactionHelper(_dbContext);
var xlsgen = new ExcelReportGenerator();
var supplierFields = new List<string>
{
"Supplier Type",
"Supplier Status",
"Supplier Name",
"FMS Supplier Number",
"EPRO Supplier Number",
"Business Registration Number",
"Business Registration Number Expiry Date",
"Business Registration Region",
"Company Address",
"Contact Person Name",
"Contact Person Position",
"Contact Email",
"Contact Phone Number (Office)",
"Fax Number",
"Procurement Category 1",
"Procurement Category 2",
"Procurement Category 3",
"Pre-Registration Invited by Buyer Date",
"Buyer and Position for Pre-Registration Invitation",
"Pre-Registration Submitted by Supplier Date",
"Pre-Registration Checked by Buyer Date",
"Full Registration Invited by Buyer Date",
"Buyer and Position for Full Registration Invitation",
"Full Registration Submitted by Supplier Date",
"Full Registration Checked by Buyer Date",
//"Full Registration Approved in FMS Date",
"Suspension Start Date",
"Suspension End Date",
"Suspension Remarks",
"Overall Performance Score",
"Termination Start Date",
"Termination Remarks"
};
List<Type> columnTypes = supplierFields.Select(_ => typeof(string)).ToList();
int currentRow = 1;
var sheet = xlsgen.GetWorksheet("Raw Data");
xlsgen.CreateHeader(supplierFields);
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity);
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMaster.xlsx");
return proFileDto;
}
小結
取消原本先全部Deserialize存集合
直接從MongoDB Cursor批次取得資料,並馬上透過ConstructTableFromData轉成表格格式寫入Excel
追蹤目前寫入的列數currentRow,方便分批寫入時定位下一行
WriteRows方法可幫助寫入多列資料並做型別轉換
只呼叫一次CreateHeader
這樣即能有效減低記憶體消耗,尤其適合資料量很大的情況。
有任何細節想調整,或是想知道ConstructTableFromData範例,都可以再問我!
/*
{"timestamp":"2025-04-11T02:00:19.951Z",
"data":{"generateReportQuery":{"reportType":"SupplierMaster","objectId":"YWQ2ODRiOTEtMTE164UEGBGR+yHDb3eS16/L9Cb47tarDLrXd5V+dTSqVa2XdUEeE5GItw=="}}}
*/
public async Task<ProFileItemUpdateDto> Create()
{
var filter = BsonDocument.Parse(_dto.JsonQuery);
var mongoClient = (_dbContext as AbstractDbContext).MongoClient;
//Convert all category id with ObjectID support
// Navigate to the $in array in the document structure
if (filter.Contains("$and"))
{
var andArray = filter["$and"]?.AsBsonArray ?? null;
// Iterate through each condition to find "Categories"
if (andArray != null)
{
foreach (var condition in andArray)
{
var condDoc = condition?.AsBsonDocument ?? null;
if (condDoc.Contains("Categories"))
{
var categories = condDoc["Categories"]?.AsBsonDocument ?? null;
if (categories.Contains("$elemMatch"))
{
var elemMatch = categories["$elemMatch"]?.AsBsonDocument ?? null;
if (elemMatch.Contains("CategoryId"))
{
var categoryId = elemMatch["CategoryId"]?.AsBsonDocument ?? null;
if (categoryId.Contains("$in"))
{
var inArray = categoryId["$in"]?.AsBsonArray ?? null;
// Convert string IDs to ObjectId and replace $in array
var objectIdArray = new BsonArray(inArray.Select(id => new ObjectId(id.AsString)));
categoryId["$in"] = objectIdArray;
}
}
}
}
}
}
}
DateTimeConvertor.ReplaceIsoDateStringsInDocument(filter);
//throw new Exception(filter.ToJson(new JsonWriterSettings { Indent = true }));
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection<BsonDocument>("ProSupplierMasterInfo");
dbHelper = new ReportingServicesDbTransactionHelper(_dbContext);
var xlsgen = new ExcelReportGenerator();
// 建立欄位
var colFields = new List<string>
{
"Supplier Type",
"Supplier Status",
"Supplier Name",
"FMS Supplier Number",
"EPRO Supplier Number",
"Business Registration Number",
"Business Registration Number Expiry Date",
"Business Registration Region",
"Company Address",
"Contact Person Name",
"Contact Person Position",
"Contact Email",
"Contact Phone Number (Office)",
"Fax Number",
"Procurement Category 1",
"Procurement Category 2",
"Procurement Category 3",
"Pre-Registration Invited by Buyer Date",
"Buyer and Position for Pre-Registration Invitation",
"Pre-Registration Submitted by Supplier Date",
"Pre-Registration Checked by Buyer Date",
"Full Registration Invited by Buyer Date",
"Buyer and Position for Full Registration Invitation",
"Full Registration Submitted by Supplier Date",
"Full Registration Checked by Buyer Date",
//"Full Registration Approved in FMS Date",
"Suspension Start Date",
"Suspension End Date",
"Suspension Remarks",
"Overall Performance Score",
"Termination Start Date",
"Termination Remarks"
};
xlsgen.CreateHeader(colFields);
var columnTypes = colFields.Select(x => typeof(string)).ToList();
int currentRow = 1;
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity);
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMasterReport.xlsx");
return proFileDto;
}
}
private List<List<string>> ConstructTableFromData(ProSupplierMasterInfoEntityDto entity)
{
var rows = new List<List<string>>();
// build up the table
var supplierSuspendData = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>().LastOrDefault(item => item.SupplierId == entity.Id);
var supplierTerminationData = dbHelper.GetReadOnlyCollectionQuery<ProSupplierTerminationEntityDto>().LastOrDefault(item => item.SupplierId == entity.Id);
var supplierInvitedData = dbHelper.GetReadOnlyCollectionQuery<ProInviteUserEntityDto>().FirstOrDefault(item => item.UserId == entity.Id);
var addr1 = "";
var addr2 = "";
if (entity?.ContactInformation != null)
{
if(entity?.ContactInformation.Addresses != null)
{
addr1 = entity?.ContactInformation?.Addresses.Count > 0 ?
(entity?.ContactInformation?.Addresses[0]?.Addr1 +
((entity?.ContactInformation?.Addresses[0]?.Addr2 != null && entity?.ContactInformation?.Addresses[0]?.Addr2 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr2) : "" ?? "") +
((entity?.ContactInformation?.Addresses[0]?.Addr3 != null && entity?.ContactInformation?.Addresses[0]?.Addr3 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr3) : "" ?? "") +
((entity?.ContactInformation?.Addresses[0]?.Addr4 != null && entity?.ContactInformation?.Addresses[0]?.Addr4 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr4) : "" ?? "")) :
"";
}
}
if (entity?.Addresses != null)
{
addr2 = entity?.Addresses.Count > 0 ?
(entity?.Addresses[0]?.Addr1 +
((entity?.Addresses[0]?.Addr2 != null && entity?.Addresses[0]?.Addr2 != "") ? (", " + entity?.Addresses[0]?.Addr2) : "" ?? "") +
((entity?.Addresses[0]?.Addr3 != null && entity?.Addresses[0]?.Addr3 != "") ? (", " + entity?.Addresses[0]?.Addr3) : "" ?? "") +
((entity?.Addresses[0]?.Addr4 != null && entity?.Addresses[0]?.Addr4 != "") ? (", " + entity?.Addresses[0]?.Addr4) : "" ?? "")) :
"";
}
var addr = addr1 == "" ? addr2 : addr1;
var ctName = "";
var ctPosition = "";
var ctEmail = "";
var ctTel = "";
var ctFax = "";
if(entity?.ContactPerson != null)
{
ctName = entity.ContactPerson?.FirstName ?? "" + (entity.ContactPerson?.LastName != null ? ", " + entity.ContactPerson?.LastName : "") ?? "";
ctPosition = entity.ContactPerson?.Position ?? "";
ctEmail = entity.ContactPerson?.EmailAddress ?? "";
ctTel = entity.ContactPerson?.Tel?.TelCode + entity.ContactPerson?.Tel?.TelNo ?? "";
ctFax = entity.ContactPerson?.Fax?.TelCode + entity.ContactPerson?.Fax?.TelNo ?? "";
}
var categories = new List<ProCategoryEntityDto>();
var cat1_text = "";
var cat2_text = "";
var cat3_text = "";
if (entity.Categories != null)
{
if (entity.Categories?.Count > 0)
{
// Find the primary cat first
ProCategoryEntityDto catData = null;
ProSupplierCategory proCat = entity.Categories.FirstOrDefault(item => item.IsPrimary == true);
var _count = 0;
if (proCat != null)
{
catData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == proCat.CategoryId);
categories.Add(catData);
_count++;
}
foreach (var cat in entity.Categories)
{
if (_count == 3) break;
if (cat.IsPrimary != true)
{
catData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == cat.CategoryId);
categories.Add(catData);
}
_count++;
}
}
}
if(categories.Count > 0 && categories[0] != null)
{
var curCat = categories[0];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat1_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat1_text += curCat?.Description?.Eng ?? "";
}
if (categories.Count > 1 && categories[1] != null)
{
var curCat = categories[1];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat2_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat2_text += curCat?.Description?.Eng ?? "";
}
if (categories.Count > 2 && categories[2] != null)
{
var curCat = categories[2];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat3_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat3_text += curCat?.Description?.Eng ?? "";
}
var inviter = new List<Dtos.Base.UserInfoBase>();
if(entity.Inviter != null)
{
inviter = entity.Inviter;
}
var row = new List<string>()
{
entity.RegistrationType == RegistrationTypeEnum.PreRegistration ? GetEnumDescription(entity.RegistrationType) : entity.ClassificationIndicator.ToString() ?? "", // Supplier Type
entity.Status.ToString() ?? "",// Supplier Status
entity.CompanyName ?? "", // Supplier Name
entity.FmsSupplierId ?? "",// FMS Supplier Number
entity.SupplierCode ?? "",// EPRO Supplier Number
entity.BrCertificateNo ?? "",// Business Registration Number
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.BrExpiryDateDateTimeObj) ?? "",// Business Registration Number Expiry Date
entity.RegisteredCountry ?? "",// Business Registration Region
addr ?? "",// Company Address
ctName,// Contact Person Name
ctPosition, // Contact Person Position
ctEmail, // Contact Email
ctTel, // Contact Phone Number (Office)
ctFax, // Fax Number
cat1_text, // Procurement Category 1
cat2_text, // Procurement Category 2
cat3_text, // Procurement Category 3
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.DateCreated) ?? "", //Pre-Registration Invited by Buyer Date
inviter.Count > 0 ? (inviter[0] ?.UserName) : "" ?? "", // Buyer and Position for Pre-Registration Invitation
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.PreRegistrationFirstSubmissionDate) ?? "", // Pre-Registration Submitted by Supplier Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.PreRegistrationApprovalDate) ?? "", // Pre-Registration Checked by Buyer Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierInvitedData?.DateCreated) ?? "", // Full Registration Invited by Buyer Date
inviter.Count > 0 ? (inviter[0] ?.UserName) : "" ?? "", // Buyer and Position for Full Registration Invitation
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.FullRegistrationFirstSubmissionDate) ?? "",// Full Registration Submitted by Supplier Date
//"",// TODO: Full Registration Checked by Buyer Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.FullRegistrationApprovalDate) ?? "",// Full Registration Approved in FMS Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierSuspendData?.StartDateTime) ?? "",// Suspension Start Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierSuspendData?.EndDateTime) ?? "",// Suspension End Date
supplierSuspendData?.Reason ?? "",// Suspension Remarks
entity.PerformanceScore ?.ToString() ?? "", // Overall Performance Score
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierTerminationData?.StartDateTime) ?? "",// Termination Start Date
supplierTerminationData?.Reason ?? ""// Termination Remarks
};
rows.Add(row);
return rows;
}
}
然後調整 ConstructTableFromData 用字典讀取
csharp Copy code
private List<List<string>> ConstructTableFromData(ProSupplierMasterInfoEntityDto entity,
Dictionary<Guid, ProSupplierSuspendEntityDto> suspendDataDict,
Dictionary<Guid, ProSupplierTerminationEntityDto> terminationDataDict,
Dictionary<Guid, ProInviteUserEntityDto> inviteUserDict,
Dictionary<Guid, ProCategoryEntityDto> categoryDict)
{
var rows = new List<List<string>>();
// 讀快取字典
var supplierSuspendData = suspendDataDict.TryGetValue(entity.Id, out var suspend) ? suspend : null;
var supplierTerminationData = terminationDataDict.TryGetValue(entity.Id, out var termination) ? termination : null;
var supplierInvitedData = inviteUserDict.TryGetValue(entity.Id, out var invite) ? invite : null;
// 下面 categories 也改用快取字典查詢
// 你的原本邏輯,只要用 categoryDict 替代 dbHelper 查詢即可
2️⃣ MongoDB 篩選索引優化
確認 filter 條件的索引是否適當(特別是 DateModified)
可以逐步測試 Mongo shell 並索引優化
3️⃣ MongoDB.Driver 查詢參數優化
將 .SortByDescending(x => x["DateModified"]) 改用 MongoDB 索引欄位名稱字串指定,減少反射開銷
設定適當BatchSize如.Find(filter).Sort(...).BatchSize(1000),平衡效能
4️⃣ Excel 寫檔可以嘗試把常用字串先在記憶體轉換完成,減少彈性運算時間
5️⃣ 多執行緒(併發)處理(進階)
分區查詢或分頁查詢多執行緒平行處理,但要注意 Excel 寫入同步問題
範例整合(修正你的Create()主要部分) csharp Copy code
// 取得所有關聯資料快取
var suspendDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>().ToList();
var suspendDataDict = suspendDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var terminationDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierTerminationEntityDto>().ToList();
var terminationDataDict = terminationDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var inviteUserList = dbHelper.GetReadOnlyCollectionQuery<ProInviteUserEntityDto>().ToList();
var inviteUserDict = inviteUserList.GroupBy(x => x.UserId)
.ToDictionary(g => g.Key, g => g.FirstOrDefault());
var categoryList = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToList();
var categoryDict = categoryList.ToDictionary(x => x.Id);
int currentRow = 1;
using (var cursor = await collection.Find(filter).SortByDescending("DateModified").ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity, suspendDataDict, terminationDataDict, inviteUserDict, categoryDict);
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
}
補充說明
這樣速度提升非常顯著,從「每筆entity多次DB查詢」→「前置整批快取」改為「純Dictionary查找」
最大的效能殺手通常是頻繁同步DB取資料
如果資料量太大,也可分批快取或分批查詢處理,避免一次載入過多
如果你需要,我可以幫你進一步示範如何多線程快取、或怎麼實作分批分段處理。
希望這些建議能幫你很快解決Timeout問題!
(B) 延遲查詢(Lazy Loading)或查詢時批次預先快取
例如依需求批次「滑動視窗」快取,查完一批entity,就查對應批次的關聯資料並馬上處理。
(C) 條件索引優化與精準查詢
保證索引優化,過濾篩選有效,避免讀取大量無用資料。
降低不必要欄位拉取(.Project()部分),減少緩存大小。
4. 其他建議
總結 作法 優點 缺點或風險 適用情況 一次快取所有關聯資料 實作簡單,查詢快 可能耗用過多記憶體 小量到中量Data 分批依主資料ID快取關聯資料 控制記憶體、針對批次查詢關聯數據 較複雜、可能多次查詢資料庫 大量資料時最佳實踐 延遲查詢,分次處理 容易控制系統資源 實作較麻煩,代價是I/O時間分散 特殊需求下彈性最高
若你能提供目前關聯資料的規模(比如 Suspend 資料量、Category數),我也可以幫你評估一個合理的預設批次大小及示範分批快取的碼。
或需要我幫你寫更完整的分批快取+分批產生Excel範例,也歡迎說!
private List<List<string>> ConstructTableFromData(ProSupplierMasterInfoEntityDto entity, Dictionary<Guid, ProCategoryEntityDto> categoryDict)
{
var rows = new List<List<string>>();
// 假設 entity.Categories 是 List<ProSupplierCategory>,有 CategoryId 和 IsPrimary
var categories = new List<ProCategoryEntityDto>();
if (entity.Categories != null && entity.Categories.Count > 0)
{
// 先找 primary category
var primaryCat = entity.Categories.FirstOrDefault(c => c.IsPrimary);
if (primaryCat != null && categoryDict.TryGetValue(primaryCat.CategoryId, out var catData))
{
categories.Add(catData);
}
// 接著找其它 category (最多三個)
foreach (var cat in entity.Categories)
{
if (categories.Count == 3) break;
if (!cat.IsPrimary && categoryDict.TryGetValue(cat.CategoryId, out catData))
{
categories.Add(catData);
}
}
}
// 建立文本欄位
string FormatCatText(ProCategoryEntityDto cat)
{
if (cat == null) return "";
string parentText = "";
if (cat.ParentId != null && categoryDict.TryGetValue(cat.ParentId.Value, out var parentCat))
{
parentText = string.IsNullOrEmpty(parentCat.Description?.Eng) ? "" : parentCat.Description.Eng + " > ";
}
return parentText + (cat.Description?.Eng ?? "");
}
var cat1_text = categories.Count > 0 ? FormatCatText(categories[0]) : "";
var cat2_text = categories.Count > 1 ? FormatCatText(categories[1]) : "";
var cat3_text = categories.Count > 2 ? FormatCatText(categories[2]) : "";
// 之後用 cat1_text, cat2_text, cat3_text 填入回傳的 row 內
// 範例(簡略)
var row = new List<string>()
{
// 其他欄位 ...
cat1_text,
cat2_text,
cat3_text,
// 其他欄位 ...
};
rows.Add(row);
return rows;
}
3. 呼叫範例修改 csharp Copy code
// 預先快取 category 字典
var categoryList = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToList();
var categoryDict = categoryList.ToDictionary(x => x.Id);
var curEntityData = ConstructTableFromData(entity, categoryDict);
總結
用字典 lookup 取代資料庫查詢,大幅提升速度
加入 categoryDict 做為輔助參數,避免 ConstructTableFromData 再去DB查詢
保持邏輯清晰,修改相對簡單
需要我也可幫你改寫完整整合版或Batch快取示範!
/*
{"timestamp":"2025-04-11T02:00:19.951Z",
"data":{"generateReportQuery":{"reportType":"SupplierMaster","objectId":"YWQ2ODRiOTEtMTE164UEGBGR+yHDb3eS16/L9Cb47tarDLrXd5V+dTSqVa2XdUEeE5GItw=="}}}
*/
public async Task<ProFileItemUpdateDto> Create()
{
var filter = BsonDocument.Parse(_dto.JsonQuery);
var mongoClient = (_dbContext as AbstractDbContext).MongoClient;
//Convert all category id with ObjectID support
// Navigate to the $in array in the document structure
if (filter.Contains("$and"))
{
var andArray = filter["$and"]?.AsBsonArray ?? null;
// Iterate through each condition to find "Categories"
if (andArray != null)
{
foreach (var condition in andArray)
{
var condDoc = condition?.AsBsonDocument ?? null;
if (condDoc.Contains("Categories"))
{
var categories = condDoc["Categories"]?.AsBsonDocument ?? null;
if (categories.Contains("$elemMatch"))
{
var elemMatch = categories["$elemMatch"]?.AsBsonDocument ?? null;
if (elemMatch.Contains("CategoryId"))
{
var categoryId = elemMatch["CategoryId"]?.AsBsonDocument ?? null;
if (categoryId.Contains("$in"))
{
var inArray = categoryId["$in"]?.AsBsonArray ?? null;
// Convert string IDs to ObjectId and replace $in array
var objectIdArray = new BsonArray(inArray.Select(id => new ObjectId(id.AsString)));
categoryId["$in"] = objectIdArray;
}
}
}
}
}
}
}
DateTimeConvertor.ReplaceIsoDateStringsInDocument(filter);
//throw new Exception(filter.ToJson(new JsonWriterSettings { Indent = true }));
var collection = mongoClient.GetDatabase("SupplierServices")
.GetCollection<BsonDocument>("ProSupplierMasterInfo");
dbHelper = new ReportingServicesDbTransactionHelper(_dbContext);
var xlsgen = new ExcelReportGenerator();
// 建立欄位
var colFields = new List<string>
{
"Supplier Type",
"Supplier Status",
"Supplier Name",
"FMS Supplier Number",
"EPRO Supplier Number",
"Business Registration Number",
"Business Registration Number Expiry Date",
"Business Registration Region",
"Company Address",
"Contact Person Name",
"Contact Person Position",
"Contact Email",
"Contact Phone Number (Office)",
"Fax Number",
"Procurement Category 1",
"Procurement Category 2",
"Procurement Category 3",
"Pre-Registration Invited by Buyer Date",
"Buyer and Position for Pre-Registration Invitation",
"Pre-Registration Submitted by Supplier Date",
"Pre-Registration Checked by Buyer Date",
"Full Registration Invited by Buyer Date",
"Buyer and Position for Full Registration Invitation",
"Full Registration Submitted by Supplier Date",
"Full Registration Checked by Buyer Date",
//"Full Registration Approved in FMS Date",
"Suspension Start Date",
"Suspension End Date",
"Suspension Remarks",
"Overall Performance Score",
"Termination Start Date",
"Termination Remarks"
};
xlsgen.CreateHeader(colFields);
var columnTypes = colFields.Select(x => typeof(string)).ToList();
var suspendDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierSuspendEntityDto>().ToList();
var suspendDataDict = suspendDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var terminationDataList = dbHelper.GetReadOnlyCollectionQuery<ProSupplierTerminationEntityDto>().ToList();
var terminationDataDict = terminationDataList.GroupBy(x => x.SupplierId)
.ToDictionary(g => g.Key, g => g.LastOrDefault());
var inviteUserList = dbHelper.GetReadOnlyCollectionQuery<ProInviteUserEntityDto>().ToList();
var inviteUserDict = inviteUserList.GroupBy(x => x.UserId)
.ToDictionary(g => g.Key, g => g.FirstOrDefault());
var categoryList = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().ToList();
var categoryDict = categoryList.ToDictionary(x => x.Id);
int currentRow = 1;
using (var cursor = await collection.Find(filter).SortByDescending(x => x["DateModified"]).ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var doc in batch)
{
var entity = BsonSerializer.Deserialize<ProSupplierMasterInfoEntityDto>(doc);
if (entity != null)
{
var curEntityData = ConstructTableFromData(entity, suspendDataDict, terminationDataDict, inviteUserDict, categoryDict);
xlsgen.WriteRows(currentRow, curEntityData, columnTypes);
currentRow += curEntityData.Count;
}
}
}
}
using (MemoryStream outputStream = new MemoryStream())
{
xlsgen.Save(outputStream);
var proFileDto = await SendToMinio(outputStream, "SupplierMasterReport.xlsx");
return proFileDto;
}
}
private List<List<string>> ConstructTableFromData(ProSupplierMasterInfoEntityDto entity,
Dictionary<ObjectId?, ProSupplierSuspendEntityDto> suspendDataDict,
Dictionary<ObjectId?, ProSupplierTerminationEntityDto> terminationDataDict,
Dictionary<ObjectId?, ProInviteUserEntityDto> inviteUserDict,
Dictionary<ObjectId?, ProCategoryEntityDto> categoryDict)
{
var rows = new List<List<string>>();
// build up the table
var supplierSuspendData = suspendDataDict.TryGetValue(entity.Id, out var suspend) ? suspend : null;
var supplierTerminationData = terminationDataDict.TryGetValue(entity.Id, out var termination) ? termination : null;
var supplierInvitedData = inviteUserDict.TryGetValue(entity.Id, out var invite) ? invite : null;
var addr1 = "";
var addr2 = "";
if (entity?.ContactInformation != null)
{
if(entity?.ContactInformation.Addresses != null)
{
addr1 = entity?.ContactInformation?.Addresses.Count > 0 ?
(entity?.ContactInformation?.Addresses[0]?.Addr1 +
((entity?.ContactInformation?.Addresses[0]?.Addr2 != null && entity?.ContactInformation?.Addresses[0]?.Addr2 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr2) : "" ?? "") +
((entity?.ContactInformation?.Addresses[0]?.Addr3 != null && entity?.ContactInformation?.Addresses[0]?.Addr3 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr3) : "" ?? "") +
((entity?.ContactInformation?.Addresses[0]?.Addr4 != null && entity?.ContactInformation?.Addresses[0]?.Addr4 != "") ? (", " + entity?.ContactInformation?.Addresses[0]?.Addr4) : "" ?? "")) :
"";
}
}
if (entity?.Addresses != null)
{
addr2 = entity?.Addresses.Count > 0 ?
(entity?.Addresses[0]?.Addr1 +
((entity?.Addresses[0]?.Addr2 != null && entity?.Addresses[0]?.Addr2 != "") ? (", " + entity?.Addresses[0]?.Addr2) : "" ?? "") +
((entity?.Addresses[0]?.Addr3 != null && entity?.Addresses[0]?.Addr3 != "") ? (", " + entity?.Addresses[0]?.Addr3) : "" ?? "") +
((entity?.Addresses[0]?.Addr4 != null && entity?.Addresses[0]?.Addr4 != "") ? (", " + entity?.Addresses[0]?.Addr4) : "" ?? "")) :
"";
}
var addr = addr1 == "" ? addr2 : addr1;
var ctName = "";
var ctPosition = "";
var ctEmail = "";
var ctTel = "";
var ctFax = "";
if(entity?.ContactPerson != null)
{
ctName = entity.ContactPerson?.FirstName ?? "" + (entity.ContactPerson?.LastName != null ? ", " + entity.ContactPerson?.LastName : "") ?? "";
ctPosition = entity.ContactPerson?.Position ?? "";
ctEmail = entity.ContactPerson?.EmailAddress ?? "";
ctTel = entity.ContactPerson?.Tel?.TelCode + entity.ContactPerson?.Tel?.TelNo ?? "";
ctFax = entity.ContactPerson?.Fax?.TelCode + entity.ContactPerson?.Fax?.TelNo ?? "";
}
var categories = new List<ProCategoryEntityDto>();
var cat1_text = "";
var cat2_text = "";
var cat3_text = "";
if (entity.Categories != null)
{
if (entity.Categories?.Count > 0)
{
// Find the primary cat first
ProCategoryEntityDto catData = null;
ProSupplierCategory proCat = entity.Categories.FirstOrDefault(item => item.IsPrimary == true);
var _count = 0;
if (proCat != null)
{
catData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == proCat.CategoryId);
categories.Add(catData);
_count++;
}
foreach (var cat in entity.Categories)
{
if (_count == 3) break;
if (cat.IsPrimary != true)
{
catData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == cat.CategoryId);
categories.Add(catData);
}
_count++;
}
}
}
if(categories.Count > 0 && categories[0] != null)
{
var curCat = categories[0];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat1_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat1_text += curCat?.Description?.Eng ?? "";
}
if (categories.Count > 1 && categories[1] != null)
{
var curCat = categories[1];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat2_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat2_text += curCat?.Description?.Eng ?? "";
}
if (categories.Count > 2 && categories[2] != null)
{
var curCat = categories[2];
if (curCat?.ParentId != null)
{
ProCategoryEntityDto ParentCatData = dbHelper.GetReadOnlyCollectionQuery<ProCategoryEntityDto>().FirstOrDefault(item => item.Id == curCat.ParentId);
cat3_text += string.IsNullOrEmpty(ParentCatData?.Description?.Eng) ? "" : ParentCatData?.Description?.Eng + " > ";
}
cat3_text += curCat?.Description?.Eng ?? "";
}
var inviter = new List<Dtos.Base.UserInfoBase>();
if(entity.Inviter != null)
{
inviter = entity.Inviter;
}
var row = new List<string>()
{
entity.RegistrationType == RegistrationTypeEnum.PreRegistration ? GetEnumDescription(entity.RegistrationType) : entity.ClassificationIndicator.ToString() ?? "", // Supplier Type
entity.Status.ToString() ?? "",// Supplier Status
entity.CompanyName ?? "", // Supplier Name
entity.FmsSupplierId ?? "",// FMS Supplier Number
entity.SupplierCode ?? "",// EPRO Supplier Number
entity.BrCertificateNo ?? "",// Business Registration Number
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.BrExpiryDateDateTimeObj) ?? "",// Business Registration Number Expiry Date
entity.RegisteredCountry ?? "",// Business Registration Region
addr ?? "",// Company Address
ctName,// Contact Person Name
ctPosition, // Contact Person Position
ctEmail, // Contact Email
ctTel, // Contact Phone Number (Office)
ctFax, // Fax Number
cat1_text, // Procurement Category 1
cat2_text, // Procurement Category 2
cat3_text, // Procurement Category 3
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.DateCreated) ?? "", //Pre-Registration Invited by Buyer Date
inviter.Count > 0 ? (inviter[0] ?.UserName) : "" ?? "", // Buyer and Position for Pre-Registration Invitation
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.PreRegistrationFirstSubmissionDate) ?? "", // Pre-Registration Submitted by Supplier Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.PreRegistrationApprovalDate) ?? "", // Pre-Registration Checked by Buyer Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierInvitedData?.DateCreated) ?? "", // Full Registration Invited by Buyer Date
inviter.Count > 0 ? (inviter[0] ?.UserName) : "" ?? "", // Buyer and Position for Full Registration Invitation
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.FullRegistrationFirstSubmissionDate) ?? "",// Full Registration Submitted by Supplier Date
//"",// TODO: Full Registration Checked by Buyer Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(entity.FullRegistrationApprovalDate) ?? "",// Full Registration Approved in FMS Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierSuspendData?.StartDateTime) ?? "",// Suspension Start Date
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierSuspendData?.EndDateTime) ?? "",// Suspension End Date
supplierSuspendData?.Reason ?? "",// Suspension Remarks
entity.PerformanceScore ?.ToString() ?? "", // Overall Performance Score
DateTimeConvertor.convertTimeToTimeZoneWithFormat(supplierTerminationData?.StartDateTime) ?? "",// Termination Start Date
supplierTerminationData?.Reason ?? ""// Termination Remarks
};
rows.Add(row);
return rows;
}
}
把重覆有關Category的查詢改為批次一次性查出並快取,我已做了快取字典,請修改ConstructTableFromData有關Category的部份