private void btnExportReport_Click(object sender, RoutedEventArgs e) { // Create report ReportsBLL.calculateReport(Convert.ToInt32(this.lbReportYear.Content)); // Insert data into excel sheet using (ExcelPackage p = new ExcelPackage()) { // Here setting some document properties p.Workbook.Properties.Author = "YM"; p.Workbook.Properties.Title = "Sales Monthly Report"; // Create a sheet p.Workbook.Worksheets.Add("WorkSheet"); ExcelWorksheet ws = p.Workbook.Worksheets[1]; // Write to excel sheet 1 // sheet 1 table 1 = s1t1, sheet 1 table 2 = s1t2, sheet 1 table 3 = s1t3 int currentRow = 1; currentRow = writeToExcel("s1t1", currentRow, ws, ""); currentRow = writeToExcel("s1t2", currentRow, ws, ""); writeToExcel("s1t3", currentRow, ws, ""); // Write to excel sheet 2 currentRow = 1; p.Workbook.Worksheets.Add("WorkSheet2"); ExcelWorksheet ws2 = p.Workbook.Worksheets[2]; p.Workbook.Worksheets.Add("WorkSheet3"); ExcelWorksheet ws3 = p.Workbook.Worksheets[3]; DataTable dt = SalesBLL.getSalesAll(); if (dt.Rows.Count != 0) { foreach (DataRow dr in dt.Rows) { currentRow = writeToExcel("s2", currentRow, ws2, dr["Id"].ToString()); } // Write s2 Total writeToExcel("s2", currentRow + 2, ws2, ""); currentRow = 1; foreach (DataRow dr in dt.Rows) { currentRow = writeToExcel("s3", currentRow, ws3, dr["Id"].ToString()); } // Write s3 Total writeToExcel("s3", currentRow + 2, ws3, ""); } // Generate A File with Random name Byte[] bin = p.GetAsByteArray(); //string file = "d:\\" + Guid.NewGuid().ToString() + ".xlsx"; string savePath = saveFile(); string file = savePath; File.WriteAllBytes(file, bin); System.Windows.Forms.MessageBox.Show("檔案儲存完畢", "Message"); } }