您好:
有看到 C# 可以用NPOI 來匯出 XLSX
那想請問,可否套用 XLSX模板 來產生新的XLSX
筆如一個 TEMPLPATE.xlsx ,裡面有 sheet1,sheet_POVIT
我先將 sheet_POVIT 做好樞紐分析,由sheet1當作來源
我將資料,匯到 sheet1,讓他sheet_POVIT 有資料
然後產生一個新的 A.xlsx ,並寄送
謝謝
我是用OpenXml來複製現有的Excel工作表, 然後在新工作表修改【值】。
using (var memoryStream = new MemoryStream())
{
//用Openxml複製工作表
using (var workbook = new XLWorkbook(HttpContext.Current.Server.MapPath("~/App_Data/範本.xlsx")))
{
workbook.SaveAs(memoryStream);
//用Openxml複製
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(memoryStream, true))
{
WorkbookPart workbookPart = doc.WorkbookPart;
var dd = query.StartDate.Date; //報表查詢起日
while (dd <= query.EndDate.Date)
{
//複製的來源工作表
OpenXmlSpreadsheetService.CopyWorksheetByName(
doc, workbookPart,
sourceSheetName: "工作表1",
newSheetName: dd.Day.ToString());
dd = dd.AddDays(1);
}
//儲存
workbookPart.Workbook.Save();
}
}
using (var workbook = new XLWorkbook(memoryStream))
{
/*後續資料處理*/
}
}
private void CopyWorksheetByName(
SpreadsheetDocument doc, WorkbookPart workbookPart,
string sourceSheetName, string newSheetName)
{
//取得要複製的來源工作表
WorksheetPart sourceSheetPart = (WorksheetPart)workbookPart.GetPartById(
workbookPart.Workbook.Descendants<Sheet>()
.Where(s => s.Name.Value.Equals(sourceSheetName))
.First()
.Id);
//利用 AddPart 來進行複製
SpreadsheetDocument tempSheet = SpreadsheetDocument.Create(new MemoryStream(), doc.DocumentType);
WorkbookPart tempWorkbookPart = tempSheet.AddWorkbookPart();
WorksheetPart tempWorksheetPart = tempWorkbookPart.AddPart<WorksheetPart>(sourceSheetPart);
//新增 sheet 並與工作表進行關聯
WorksheetPart clonedSheet = workbookPart.AddPart<WorksheetPart>(tempWorksheetPart);
//新增新的工作表到主要的活頁簿中
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
Sheet copiedSheet = new Sheet()
{
Name = newSheetName,
Id = workbookPart.GetIdOfPart(clonedSheet),
SheetId = (uint)sheets.ChildElements.Count + 1,
};
sheets.Append(copiedSheet);
}
參考:
如果需要改到圖表的公式:https://social.msdn.microsoft.com/Forums/en-US/cc811704-411d-43e9-8b11-3901571aaf9d/open-xml-excel-charts?forum=oxmlsdk