private void saveExcel_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { string name = saveExcel.FileName; // Get JSON text JObject obj = JObject.Parse(jsonContainer.Text); obj.AddFirst(new JProperty("name", rootName)); string jsonString = "[" + obj.ToString() + "]"; // Create a Workbook object Workbook workbook = new Workbook(); Worksheet worksheet = workbook.Worksheets[0]; // Set Styles CellsFactory factory = new CellsFactory(); Style style = factory.CreateStyle(); style.HorizontalAlignment = TextAlignmentType.Center; style.Font.Color = System.Drawing.Color.BlueViolet; style.Font.IsBold = true; // Set JsonLayoutOptions JsonLayoutOptions options = new JsonLayoutOptions(); options.ConvertNumericOrDate = true; options.TitleStyle = style; options.ArrayAsTable = true; // Import JSON Data JsonUtility.ImportData(jsonString, worksheet.Cells, 0, 0, options); // Save Excel file workbook.Save(@name); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Instantiating a Workbook object Workbook workbook = new Workbook(); Worksheet worksheet = workbook.Worksheets[0]; // Read File string jsonInput = File.ReadAllText(dataDir + "Test.json"); // Set Styles CellsFactory factory = new CellsFactory(); Style style = factory.CreateStyle(); style.HorizontalAlignment = TextAlignmentType.Center; style.Font.Color = System.Drawing.Color.BlueViolet; style.Font.IsBold = true; // Set JsonLayoutOptions JsonLayoutOptions options = new JsonLayoutOptions(); options.TitleStyle = style; options.ArrayAsTable = true; // Import JSON Data JsonUtility.ImportData(jsonInput, worksheet.Cells, 0, 0, options); // Save Excel file workbook.Save(dataDir + "ImportingFromJson.out.xlsx"); // ExEnd:1 }
protected FrmBaseRenderService(string reportId) { _reportID = reportId; var cellsFactory = new CellsFactory(); _defaultStyle = cellsFactory.CreateStyle(); _dateTimeStyle = cellsFactory.CreateStyle(); ConfigureStyles(); }
public FrmReportRenderService() { var cellsFactory = new CellsFactory(); _headerStyle = cellsFactory.CreateStyle(); _tableTitleStyle = cellsFactory.CreateStyle(); _tableHeaderStyle = cellsFactory.CreateStyle(); _tableTotalStyle = cellsFactory.CreateStyle(); _tableRowStyle = cellsFactory.CreateStyle(); ConfigureStyles(); }
public FundingSummaryRenderService() { var cellsFactory = new CellsFactory(); _defaultStyle = cellsFactory.CreateStyle(); _textWrappedStyle = cellsFactory.CreateStyle(); _futureMonthStyle = cellsFactory.CreateStyle(); _fundingCategoryStyle = cellsFactory.CreateStyle(); _fundingSubCategoryStyle = cellsFactory.CreateStyle(); _fundLineGroupStyle = cellsFactory.CreateStyle(); _headerAndFooterStyle = cellsFactory.CreateStyle(); ConfigureStyles(); }
public DevolvedAdultEducationFundingSummaryReportRenderService() { var cellsFactory = new CellsFactory(); _defaultStyle = cellsFactory.CreateStyle(); _futureMonthStyle = cellsFactory.CreateStyle(); _fundingCategoryStyle = cellsFactory.CreateStyle(); _fundingSubCategoryStyle = cellsFactory.CreateStyle(); _fundLineGroupStyle = cellsFactory.CreateStyle(); _headerStyle = cellsFactory.CreateStyle(); _footerStyle = cellsFactory.CreateStyle(); ConfigureStyles(); }
public FundingSummaryReportRenderService() { var cellsFactory = new CellsFactory(); _defaultStyle = cellsFactory.CreateStyle(); _reportTitleStyle = cellsFactory.CreateStyle(); _deliverableGroupStyle = cellsFactory.CreateStyle(); _deliverableSubGroupStyle = cellsFactory.CreateStyle(); _deliverableLineStyle = cellsFactory.CreateStyle(); _headerAndFooterStyle = cellsFactory.CreateStyle(); _reportMonthlyTotalsStyle = cellsFactory.CreateStyle(); ConfigureStyles(); }
/// <summary> /// Hàm tạo tile cho xuất Excell /// </summary> /// <param name="upperLeft"></param> /// <param name="upperRight"></param> /// <param name="sheetReport"></param> /// <param name="Title"></param> private void CreateTitle(string upperLeft, string upperRight, Worksheet sheetReport, string Title, int size) { //Add range title Range rangeTitle = sheetReport.Cells.CreateRange(upperLeft, upperRight); //Merage title rangeTitle.UnMerge(); rangeTitle.Merge(); //Put text to title rangeTitle.PutValue(Title, false, true); //Set style range title Style styleTitle = new CellsFactory().CreateStyle(); styleTitle.Font.IsBold = true; styleTitle.Font.Color = Color.Black; styleTitle.Font.Size = size; //styleTitle.Font.Name = "Times New Roman"; styleTitle.Font.Name = "Calibri"; styleTitle.HorizontalAlignment = TextAlignmentType.Center; rangeTitle.SetStyle(styleTitle); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create a Style object using CellsFactory class CellsFactory cf = new CellsFactory(); Style st = cf.CreateStyle(); // Set the Style fill color to Yellow st.Pattern = BackgroundType.Solid; st.ForegroundColor = Color.Yellow; // Create a workbook and set its default style using the created Style object Workbook wb = new Workbook(); wb.DefaultStyle = st; // Save the workbook wb.Save(dataDir + "output_out.xlsx"); // ExEnd:1 }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create a Style object using CellsFactory class CellsFactory cf = new CellsFactory(); Style st = cf.CreateStyle(); // Set the Style fill color to Yellow st.Pattern = BackgroundType.Solid; st.ForegroundColor = Color.Yellow; // Create a workbook and set its default style using the created Style object Workbook wb = new Workbook(); wb.DefaultStyle = st; // Save the workbook wb.Save(dataDir + "output_out.xlsx"); // ExEnd:1 }
public static bool ToExcel <T>(string destPath, List <T> datas, string name, int rowNum, bool isOpen = false) { var dataTable = Utils.ToDataTable <T>(datas); return(ToExcelPrivate(name, destPath, (Worksheet worksheet) => { for (int i = 0; i < dataTable.Rows.Count; i++) { //var rowActive = 3 + i; for (int j = 0; j < dataTable.Columns.Count; j++) { var s = dataTable.Rows[i][j]; worksheet.Cells[rowNum, j].GetStyle().Font.Size = 11; var style = new CellsFactory().CreateStyle(); style.Font.Size = 11; worksheet.Cells[rowNum, j].SetStyle(style); worksheet.Cells[rowNum, j].PutValue(dataTable.Rows[i][j]); } rowNum++; } //((ExcelRangeBase)worksheet.Cells["A1"]).LoadFromArrays((IEnumerable<object[]>)datas.Select((IList<string> data) => data.ToArray())); }, isOpen));// ? dataTable : null; }
public static void Run() { //Output directory string outputDir = RunExamples.Get_OutputDirectory(); // Create a Style object using CellsFactory class CellsFactory cf = new CellsFactory(); Style st = cf.CreateStyle(); // Set the Style fill color to Yellow st.Pattern = BackgroundType.Solid; st.ForegroundColor = Color.Yellow; // Create a workbook and set its default style using the created Style object Workbook wb = new Workbook(); wb.DefaultStyle = st; // Save the workbook wb.Save(outputDir + "outputUsingCellsFactory.xlsx"); Console.WriteLine("UsingCellsFactory executed successfully."); }
/// <summary> /// Tạo mẫu cho Excel cho so sánh theo giai đoạn /// </summary> /// <param name="gradationID"></param> /// <param name="year"></param> /// <param name="typeID"></param> /// <returns></returns> public ActionResult CreateExcelGradationCompareLastYear(int year, int month, string reportTypeID) { WorkbookDesigner designer = new WorkbookDesigner(); string templatePath = "~/Content/Report/ReportForTotalPayment.xlsx"; // Get đường dẫn templatePath = System.Web.HttpContext.Current.Server.MapPath(templatePath); designer.Workbook = new DongA.Core.DongAExcel().OpenExcelFile(templatePath); designer.Workbook.CalculateFormula(); WorksheetCollection workSheets = designer.Workbook.Worksheets; Worksheet sheetReport = designer.Workbook.Worksheets[0]; // Tạo title string typeReport = "So sánh - Theo tháng - So với tháng trước"; string text = string.Format("Tháng: {0}/{1}", month, year); // Tạo title CreateTitle("A2", "U2", sheetReport, typeReport, 14); // Tạo title detailt string titleDetailt = text; CreateTitle("A3", "U3", sheetReport, titleDetailt, 12); // xóa từ/đến sheetReport.Cells["L4"].PutValue(""); sheetReport.Cells["P4"].PutValue(""); // Create Chart Line //Chart reference Aspose.Cells.Charts.Chart leadSourceLine; //Add Pie Chart int chartIndex = sheetReport.Charts.Add(ChartType.Column3DClustered, 6, 0, 30, 13); leadSourceLine = sheetReport.Charts[chartIndex]; //// Canh hiển thị CategoryAxis nghiên phù hợp //leadSourceLine.CategoryAxis.TickLabels.RotationAngle = 45; //Chart title leadSourceLine.Title.Text = string.Format("Tổng doanh số chi trả {0}/{1} so với tháng trước và so với cùng kì năm trước", month, year); leadSourceLine.Title.Font.Color = Color.Silver; // Set width cho column sheetReport.Cells.SetColumnWidthPixel(15, 220); List <ReportForTotalPayment> listReportData = new ReportBL().DataReportTPCompareForMonth(year, month, reportTypeID); // clone Object List <ReportForTotalPayment> listReportDataClone = new List <ReportForTotalPayment>(listReportData); DataTable dataTable = new DataTable(); // Theo doanh số chi trả loại hình dịch vụ if (listReportData.Count.Equals(3)) { foreach (ReportForTotalPayment item in listReportData) { item.ReportID = string.Format("Tháng {0}/{1}", item.Month, item.Year); } double totalPayment = listReportData[0].Payed - listReportData[1].Payed; double totalPaymentLastYear = listReportData[0].Payed - listReportData[2].Payed; // Object báo cáo tăng giảm so với tháng trước (%) ReportForTotalPayment dataDifference = null; dataDifference = new ReportForTotalPayment() { ReportID = "Tăng giảm so với tháng trước (%)", Payed = Math.Round(totalPayment / listReportData[1].Payed * 100, 2, MidpointRounding.ToEven), }; listReportData.Add(dataDifference); // Object báo cáo tăng giảm so với tháng trước (+/-) dataDifference = new ReportForTotalPayment() { ReportID = "Tăng giảm so với tháng trước (+/-)", Payed = Math.Round(totalPayment, 2, MidpointRounding.ToEven), }; listReportData.Add(dataDifference); // Object báo cáo tăng giảm so với cùng kì năm trước (%) dataDifference = new ReportForTotalPayment() { ReportID = "Tăng giảm so với cùng kì năm trước (%)", Payed = Math.Round(totalPaymentLastYear / listReportData[2].Payed * 100, 2, MidpointRounding.ToEven), }; listReportData.Add(dataDifference); // Object báo cáo tăng giảm so với cùng kì năm trước (+/-) dataDifference = new ReportForTotalPayment() { ReportID = "Tăng giảm so với cùng kì năm trước (+/-)", Payed = Math.Round(totalPaymentLastYear, 2, MidpointRounding.ToEven), }; listReportData.Add(dataDifference); // Add item to datatable dataTable = CreateDataTableFormart(); // Danh sách dataSet của báo cáo ngày DataSet dataReport = new DongA.Core.DongAExcel().ConvertListObjectToDataSet(listReportData); // Đổ data vào datatble mới FillData(dataReport.Tables[0], dataTable); // get data string totalRowData = "Q8:Q10"; leadSourceLine.NSeries.Add(totalRowData, true); // Get row string categoryData = "P8:P10"; leadSourceLine.NSeries.CategoryData = categoryData; // Set the names of the chart series taken from cells. leadSourceLine.NSeries[0].Name = "=Q7"; // Set plot area formatting as none and hide its border. leadSourceLine.PlotArea.Area.FillFormat.FillType = FillType.None; leadSourceLine.PlotArea.Border.IsVisible = false; // Set value axis major tick mark as none and hide axis line. // Also set the color of value axis major grid lines. leadSourceLine.ValueAxis.MajorTickMark = TickMarkType.None; leadSourceLine.ValueAxis.AxisLine.IsVisible = false; leadSourceLine.ValueAxis.MajorGridLines.Color = Color.FromArgb(217, 217, 217); // Set border Style style = new CellsFactory().CreateStyle(); style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black); if (dataTable.Rows.Count > 0) { int stepRow = 0; // total row = row start + số row hiện có int totalRow = dataTable.Rows.Count + 7; // Số dòng của row for (int a = 7; a < totalRow; a++) { int stepColumn = 0; // Số cột trong báo cáo cần hiển thị // Tổng số cột hiển thị = Số cột hiển thị bắt đầu + tổng số cột cần hiển thị int totalCol = 15 + 2; for (int b = 15; b < totalCol; b++) { // Giá trị của value trong table string valueOfTable = dataTable.Rows[stepRow][stepColumn].ToString(); // Tô màu cho các dòng có giá trị tăng giảm if (b >= 16 && a >= 10) { decimal tryParseValue = 0; decimal.TryParse(valueOfTable, out tryParseValue); style.Font.Color = Color.Green; if (tryParseValue < 0) { style.Font.Color = Color.Red; } } // Insert vào dòng cột xác định trong Excel sheetReport.Cells[a, b].PutValue(valueOfTable, true); // set style cho number style.Custom = "#,##0.00"; // set border sheetReport.Cells[a, b].SetStyle(style); // Cột tổng cộng if (b.Equals(totalCol - 1)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Trường hợp thuộc 2 dòng cuối if (a.Equals(totalRow - 1) || a.Equals(totalRow - 2)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Set lại giá trị mặt định style.Font.IsBold = false; // Tăng cột theo dòng của table stepColumn++; } // Tăng dòng của table lên stepRow++; // Set lại color cho dòng hiện tại style.Font.Color = Color.Black; } } else { sheetReport.Cells["D10"].PutValue("Không có dữ liệu"); } } // Chạy process designer.Process(); return(ExportReport("ReportGradationCompare", designer)); }
/// <summary> /// Xuất Excel theo tháng /// </summary> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <returns></returns> public ActionResult CreateExcelForDayMonthYear(DateTime fromDate, DateTime toDate, int typeID, string reportTypeID) { WorkbookDesigner designer = new WorkbookDesigner(); string templatePath = "~/Content/Report/ReportForTotalPayment.xlsx"; // Get đường dẫn templatePath = System.Web.HttpContext.Current.Server.MapPath(templatePath); designer.Workbook = new DongA.Core.DongAExcel().OpenExcelFile(templatePath); designer.Workbook.CalculateFormula(); WorksheetCollection workSheets = designer.Workbook.Worksheets; Worksheet sheetReport = designer.Workbook.Worksheets[0]; // Tạo title string typeReport = string.Empty; switch (typeID) { // Theo ngày case 1: typeReport = "Chi tiết - Theo Ngày"; // Set from day and to day sheetReport.Cells["M4"].PutValue(string.Format("{0}", fromDate.ToString("dd/MM/yyyy"))); sheetReport.Cells["Q4"].PutValue(string.Format("{0}", toDate.ToString("dd/MM/yyyy"))); break; // Theo tháng case 2: typeReport = "Chi tiết - Theo Tháng"; // Set from day and to day sheetReport.Cells["M4"].PutValue(string.Format("{0}/{1}", fromDate.Month, fromDate.Year)); sheetReport.Cells["Q4"].PutValue(string.Format("{0}/{1}", toDate.Month, toDate.Year)); break; // Theo năm default: typeReport = "Chi tiết - Theo Năm"; // Set from day and to day sheetReport.Cells["M4"].PutValue(fromDate.Year.ToString()); sheetReport.Cells["Q4"].PutValue(toDate.Year.ToString()); break; } CreateTitle("A2", "U2", sheetReport, typeReport, 14); // Trường hợp với report năm if (typeID.Equals(3)) { sheetReport.Cells["Q7"].PutValue(""); } // Create Chart Line //Chart reference Aspose.Cells.Charts.Chart leadSourceLine; //Add Pie Chart int chartIndex = sheetReport.Charts.Add(ChartType.Line, 6, 0, 30, 13); leadSourceLine = sheetReport.Charts[chartIndex]; // Canh hiển thị CategoryAxis nghiên phù hợp leadSourceLine.CategoryAxis.TickLabels.RotationAngle = 45; //Chart title leadSourceLine.Title.Text = "Tổng doanh số chi trả"; leadSourceLine.Title.Font.Color = Color.Silver; // Get data report ngày List <ReportForTotalPayment> listReportData = new List <ReportForTotalPayment>(); switch (typeID) { // Theo ngày case 1: listReportData = new ReportBL().SearchReportTPForDay(fromDate, toDate, reportTypeID); break; // Theo tháng case 2: listReportData = new ReportBL().SearchReportTPForMonth(fromDate, toDate, reportTypeID); break; // Theo năm default: listReportData = new ReportBL().SearchReportTPForYear(fromDate, toDate, reportTypeID); break; } DataTable dataTable = new DataTable(); // Set border Style style = new CellsFactory().CreateStyle(); style.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black); if (listReportData.Count > 0) { foreach (ReportForTotalPayment item in listReportData) { switch (typeID) { // Theo ngày case 1: item.ReportID = string.Concat("Ngày ", item.CreatedDate.Day, "/", item.CreatedDate.Month); break; // Theo tháng case 2: item.ReportID = string.Concat("Tháng ", item.Month, "/", item.Year); break; // Theo năm default: item.ReportID = item.Year; break; } item.Type = 0; } // Trường hợp với report năm if (typeID.Equals(3)) { dataTable = new DataTable(); // Số năm chênh lệch // Số 1 là số ngày cộng int countYear = toDate.Year - fromDate.Year + 1; // Tạo title cho colum string[] arrayItems = { "Q7", "R7", "S7", "T7", "U7" }; int countArray = 0; for (int i = fromDate.Year; i <= toDate.Year; i++) { sheetReport.Cells[arrayItems[countArray]].PutValue(i); sheetReport.Cells[arrayItems[countArray]].SetStyle(style); countArray++; } // Tạo các cột cho datatable dataTable.Columns.Add("ReportID", typeof(String)); for (int i = 1; i <= countYear; i++) { dataTable.Columns.Add(string.Concat("year", i), typeof(double)); } if (listReportData.Count > 0) { // Tạo vòng for cho 12 tháng for (int i = 1; i <= 12; i++) { List <ReportForTotalPayment> listMonths = listReportData.Where(x => x.Month == i.ToString()).ToList(); // số thứ tự theo năm int count = 1; DataRow dr = dataTable.NewRow(); dr["ReportID"] = string.Concat("Tháng ", i); foreach (ReportForTotalPayment item in listMonths) { dr[string.Concat("year", count)] = item.Payed; count++; } dataTable.Rows.Add(dr); } // add dòng tổng DataColumnCollection columns = dataTable.Columns; DataRow row = dataTable.NewRow(); row["ReportID"] = "Tổng"; int countRow = 1; string year = "year"; foreach (DataColumn col in dataTable.Columns) { string yearCol = string.Concat(year, countRow); if (col.ColumnName.Equals(yearCol)) { row[yearCol] = dataTable.Compute(string.Format("Sum({0})", yearCol), ""); countRow++; } ; } dataTable.Rows.Add(row); // Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3" // Số tháng cố định là 12 tháng // Số cột hiển thị cho biểu đồ đường string[] arrayRowData = { "Q", "R", "S", "T", "U" }; string totalRowData = string.Format("Q8:{0}{1}", arrayRowData[toDate.Year - fromDate.Year], 12 + 8 - 1); //string totalRowData = string.Format("P8:U{0}", 12 + 8 - 2); leadSourceLine.NSeries.Add(totalRowData, true); // Set the category data covering the range A2:A5. // Tổng số dòng cần hiển thị là số dòng hiện tại + số dòng trong listData -2 (trong đó 1 là dòng tổng cuối cùng) string categoryData = string.Format("P8:P{0}", 12 + 8 - 1); leadSourceLine.NSeries.CategoryData = categoryData; // Tạo cột động cho bảng dữ liệu countArray = 0; for (int i = fromDate.Year; i <= toDate.Year; i++) { leadSourceLine.NSeries[countArray].Name = string.Format("={0}", arrayItems[countArray]); switch (countArray) { case 1: // Set the 1st series fill color. leadSourceLine.NSeries[countArray].Border.Color = Color.Orange; leadSourceLine.NSeries[countArray].Area.Formatting = FormattingType.Custom; break; case 2: // Set the 1st series fill color. leadSourceLine.NSeries[countArray].Border.Color = Color.Green; leadSourceLine.NSeries[countArray].Area.Formatting = FormattingType.Custom; break; case 3: // Set the 1st series fill color. leadSourceLine.NSeries[countArray].Border.Color = Color.Blue; leadSourceLine.NSeries[countArray].Area.Formatting = FormattingType.Custom; break; case 4: // Set the 1st series fill color. leadSourceLine.NSeries[countArray].Border.Color = Color.Purple; leadSourceLine.NSeries[countArray].Area.Formatting = FormattingType.Custom; break; default: // Set the 1st series fill color. leadSourceLine.NSeries[countArray].Border.Color = Color.Pink; leadSourceLine.NSeries[countArray].Area.Formatting = FormattingType.Custom; break; } countArray++; } } } else { // Add dòng tổng vào list danh sách ReportForTotalPayment reportForTotalPayment = new ReportForTotalPayment() { ReportID = "Tổng", Payed = listReportData.Sum(item => item.Payed) }; listReportData.Add(reportForTotalPayment); // Tạo các col cho table dataTable = CreateDataTableFormart(); // Danh sách dataSet của báo cáo ngày DataSet dataReport = ConvertListObjectToDataSet(listReportData); // Đổ data vào datatble mới FillData(dataReport.Tables[0], dataTable); // Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3" string totalRowData = string.Format("Q8:Q{0}", listReportData.Count + 8 - 2); leadSourceLine.NSeries.Add(totalRowData, true); // Set the category data covering the range A2:A5. // Tổng số dòng cần hiển thị là số dòng hiện tại + số dòng trong listData -2 (trong đó 1 là dòng tổng cuối cùng) string categoryData = string.Format("P8:P{0}", listReportData.Count + 8 - 2); leadSourceLine.NSeries.CategoryData = categoryData; // Set the names of the chart series taken from cells. leadSourceLine.NSeries[0].Name = "=Q7"; // Set the 1st series fill color. //leadSourceLine.NSeries[0].Area.ForegroundColor = Color.Pink; leadSourceLine.NSeries[0].Border.Color = Color.Blue; leadSourceLine.NSeries[0].Area.Formatting = FormattingType.Custom; } // Set plot area formatting as none and hide its border. leadSourceLine.PlotArea.Area.FillFormat.FillType = FillType.None; leadSourceLine.PlotArea.Border.IsVisible = false; // Set value axis major tick mark as none and hide axis line. // Also set the color of value axis major grid lines. leadSourceLine.ValueAxis.MajorTickMark = TickMarkType.None; leadSourceLine.ValueAxis.AxisLine.IsVisible = false; leadSourceLine.ValueAxis.MajorGridLines.Color = Color.FromArgb(217, 217, 217); } if (dataTable.Rows.Count > 0) { int stepRow = 0; // total row = row start + số row hiện có int totalRow = dataTable.Rows.Count + 7; // Số dòng của row for (int a = 7; a < totalRow; a++) { int stepColumn = 0; // Số cột trong báo cáo cần hiển thị // Tổng số cột hiển thị = Số cột hiển thị bắt đầu + tổng số cột cần hiển thị // trường hợp với report chọn tháng int totalCol = 15 + 2; // trường hợp với report chọn năm if (typeID.Equals(3)) { totalCol = 15 + (toDate.Year - fromDate.Year) + 2; } for (int b = 15; b < totalCol; b++) { // Giá trị của value trong table string valueOfTable = dataTable.Rows[stepRow][stepColumn].ToString(); // Insert vào dòng cột xác định trong Excel sheetReport.Cells[a, b].PutValue(valueOfTable, true); // set style cho number style.Custom = "#,##0.00"; // set border sheetReport.Cells[a, b].SetStyle(style); // Cột tổng cộng if (b.Equals(totalCol - 1)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Trường hợp thuộc dòng cuối Tổng if (a.Equals(totalRow - 1)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Set lại giá trị mặt định style.Font.IsBold = false; // Tăng cột theo dòng của table stepColumn++; } // Tăng dòng của table lên stepRow++; } } else { sheetReport.Cells["D10"].PutValue("Không có dữ liệu"); } //sheetReport.Cells.ConvertStringToNumericValue(); // Chạy process designer.Process(); switch (typeID) { // Theo ngày case 1: return(ExportReport("ReportDay", designer)); break; // Theo tháng case 2: return(ExportReport("ReportMonth", designer)); break; // Theo năm default: return(ExportReport("ReportYear", designer)); break; } }
// Generate analytics from binary image public void PostProcessImage <T>(FileFormatStream <T> stream, PluginPostProcessImageEventInfo info) where T : FileFormatStream <T> { // Report to the user what is happening PluginServices.For(this).StatusUpdate("Generating analytics"); // Get the section we would like to investigate Section section; try { section = stream.GetSections().Single(s => s.Name == sectionName.Value); } // Not all binaries have a section with this name, or any sections at all catch { return; } // Get contents of section var bytes = stream.ReadBytes(section.ImageStart, (int)(section.ImageEnd - section.ImageStart)); // Produce frequency graph of bytes // This will produce a dictionary where the key is the byte value and the value is the number of times it occurred var freq = bytes.GroupBy(b => b).OrderBy(g => g.Key).ToDictionary(g => g.Key, g => (double)g.Count() * 100 / bytes.Length); // Write as CSV file if (Path.GetExtension(outputPath.Value) == ".csv") { var csv = new StringBuilder(); csv.AppendLine("Byte,Count"); csv.Append(string.Join(Environment.NewLine, freq.Select(f => f.Key + "," + f.Value))); File.WriteAllText(outputPath.Value, csv.ToString()); return; } // Write as XLSX file (using nuget package Aspose.Cells) var wb = new Workbook(); var sheet = wb.Worksheets[0]; // Add headers sheet.Cells["A1"].PutValue("Byte"); sheet.Cells["B1"].PutValue("Count"); // Create number format style var style = new CellsFactory().CreateStyle(); style.Custom = "@"; // Text for hex bytes column // Add data for (var row = 0; row < freq.Count; row++) { sheet.Cells["A" + (row + 2)].PutValue($"{row:X2}"); sheet.Cells["A" + (row + 2)].SetStyle(style, true); sheet.Cells["B" + (row + 2)].PutValue(freq[(byte)row]); } // Create table var list = sheet.ListObjects[sheet.ListObjects.Add("A1", "B257", hasHeaders: true)]; list.TableStyleType = TableStyleType.TableStyleMedium6; // Create chart var chart = sheet.Charts[sheet.Charts.Add(ChartType.Column, 3, 3, 40, 26)]; chart.Title.Text = "Frequency graph of data bytes"; chart.Style = 3; chart.ValueAxis.IsLogarithmic = true; chart.ValueAxis.CrossAt = 0.001; chart.ValueAxis.IsAutomaticMaxValue = false; chart.ValueAxis.MaxValue = 100; chart.ValueAxis.LogBase = 2; // Set chart data chart.SetChartDataRange("A1:B257", isVertical: true); chart.NSeries.CategoryData = "A2:A257"; chart.NSeries[0].GapWidth = 0; // 'Count' data series is at index 0 now that category has been set chart.ShowLegend = false; // Save workbook wb.Save(outputPath.Value, SaveFormat.Xlsx); }
public ActionResult CreateExcel(DateTime fromDate, DateTime toDate, string typeID, string reportTypeID) { WorkbookDesigner designer = new WorkbookDesigner(); string templatePath = "~/Content/Report/ReportDetail.xlsx"; // Get đường dẫn templatePath = System.Web.HttpContext.Current.Server.MapPath(templatePath); designer.Workbook = new DongA.Core.DongAExcel().OpenExcelFile(templatePath); designer.Workbook.CalculateFormula(); WorksheetCollection workSheets = designer.Workbook.Worksheets; Worksheet sheetReport = designer.Workbook.Worksheets[0]; // Tạo title string typeReport = string.Empty; switch (typeID) { // Theo ngày case "1": typeReport = "Chi tiết - Theo ngày"; break; // Theo tháng case "2": typeReport = "Chi tiết - Theo Tháng"; break; // Theo năm default: typeReport = "Chi tiết - Theo Năm"; break; } CreateTitle("A2", "U2", sheetReport, typeReport); switch (typeID) { // Theo ngày case "1": // Set from day and to day sheetReport.Cells["M4"].PutValue(fromDate.ToString("dd/MM/yyyy")); sheetReport.Cells["Q4"].PutValue(toDate.ToString("dd/MM/yyyy")); break; // Theo tháng case "2": // Set from day and to day sheetReport.Cells["M4"].PutValue(fromDate.ToString("MM/yyyy")); sheetReport.Cells["Q4"].PutValue(toDate.ToString("MM/yyyy")); break; // Theo năm default: // Set from day and to day sheetReport.Cells["M4"].PutValue(fromDate.Year.ToString()); sheetReport.Cells["Q4"].PutValue(toDate.Year.ToString()); break; } // Create Chart Line //Chart reference Aspose.Cells.Charts.Chart leadSourceLine; //Add Pie Chart int chartIndex = sheetReport.Charts.Add(ChartType.Line, 6, 0, 30, 13); leadSourceLine = sheetReport.Charts[chartIndex]; // Canh hiển thị CategoryAxis nghiên phù hợp leadSourceLine.CategoryAxis.TickLabels.RotationAngle = 45; //Chart title leadSourceLine.Title.Text = "Doanh số chi trả theo từng dịch vụ"; leadSourceLine.Title.Font.Color = Color.Silver; List <Report> listReportData = new List <Report>(); int typeIDForDate = int.Parse(typeID); // Danh sách ngày switch (typeID) { // Theo ngày case "1": listReportData = new ReportBL().SearchDay(fromDate, toDate, reportTypeID); break; // Theo tháng case "2": listReportData = new ReportBL().SearchMonth(fromDate, toDate, reportTypeID); break; // Theo năm default: listReportData = new ReportBL().SearchYear(fromDate, toDate, reportTypeID); break; } DataTable dataTable = new DataTable(); if (listReportData.Count > 0) { foreach (Report item in listReportData) { switch (typeID) { // Theo ngày case "1": item.ReportID = string.Concat("Ngày ", item.CreatedDate.Day, "/", item.CreatedDate.Month); break; // Theo tháng case "2": item.ReportID = string.Concat("Tháng ", item.Month, "/", item.Year); break; // Theo năm default: item.ReportID = string.Concat("Năm ", item.Year); break; } item.TongDS = item.DSChiNha + item.DSChiQuay + item.DSCK; item.Type = 0; } // Add dòng tổng vào list danh sách Report report = new Report() { ReportID = "Tổng", DSChiNha = listReportData.Sum(item => item.DSChiNha), DSChiQuay = listReportData.Sum(item => item.DSChiQuay), DSCK = listReportData.Sum(item => item.DSCK), TongDS = listReportData.Sum(item => item.TongDS) }; listReportData.Add(report); // Tạo các col cho table dataTable = CreateDataTableFormart(typeID); // Danh sách dataSet của báo cáo ngày DataSet dataReport = ConvertListObjectToDataSet(listReportData); // Đổ data vào datatble mới FillData(dataReport.Tables[0], dataTable, typeID); // Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3" string totalRowData = string.Format("Q8:S{0}", listReportData.Count + 8 - 2); leadSourceLine.NSeries.Add(totalRowData, true); // Set the category data covering the range A2:A5. // Tổng số dòng cần hiển thị là số dòng hiện tại + số dòng trong listData -2 (trong đó 1 là dòng tổng cuối cùng) string categoryData = string.Format("P8:P{0}", listReportData.Count + 8 - 2); leadSourceLine.NSeries.CategoryData = categoryData; // Set the names of the chart series taken from cells. leadSourceLine.NSeries[0].Name = "=Q7"; leadSourceLine.NSeries[1].Name = "=R7"; leadSourceLine.NSeries[2].Name = "=S7"; //leadSourceLine.NSeries[3].Name = "=T7"; // Set the 1st series fill color. leadSourceLine.NSeries[0].Border.Color = Color.Orange; leadSourceLine.NSeries[0].Area.Formatting = FormattingType.Custom; // Set the 2nd series fill color. leadSourceLine.NSeries[1].Border.Color = Color.Green; leadSourceLine.NSeries[1].Area.Formatting = FormattingType.Custom; // Set the 3rd series fill color. leadSourceLine.NSeries[2].Border.Color = Color.Blue; leadSourceLine.NSeries[2].Area.Formatting = FormattingType.Custom; //// Set the 4rd series fill color. //leadSourceLine.NSeries[3].Border.Color = Color.Purple; //leadSourceLine.NSeries[3].Area.Formatting = FormattingType.Custom; // Set plot area formatting as none and hide its border. leadSourceLine.PlotArea.Area.FillFormat.FillType = FillType.None; leadSourceLine.PlotArea.Border.IsVisible = false; // Set value axis major tick mark as none and hide axis line. // Also set the color of value axis major grid lines. leadSourceLine.ValueAxis.MajorTickMark = TickMarkType.None; leadSourceLine.ValueAxis.AxisLine.IsVisible = false; leadSourceLine.ValueAxis.MajorGridLines.Color = Color.FromArgb(217, 217, 217); } // Set border Style style = new CellsFactory().CreateStyle(); style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black); style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black); if (dataTable.Rows.Count > 0) { int stepRow = 0; // total row = row start + số row hiện có int totalRow = dataTable.Rows.Count + 7; // Số dòng của row for (int a = 7; a < totalRow; a++) { int stepColumn = 0; // Số cột trong báo cáo cần hiển thị // Tổng số cột hiển thị = Số cột hiển thị bắt đầu + tổng số cột cần hiển thị int totalCol = 15 + 5; for (int b = 15; b < totalCol; b++) { // Giá trị của value trong table string valueOfTable = dataTable.Rows[stepRow][stepColumn].ToString(); // Insert vào dòng cột xác định trong Excel sheetReport.Cells[a, b].PutValue(valueOfTable, true); // set style cho number style.Custom = "#,##0.00"; // set border sheetReport.Cells[a, b].SetStyle(style); // Cột tổng cộng if (b.Equals(totalCol - 1)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Trường hợp thuộc dòng cuối Tổng if (a.Equals(totalRow - 1)) { sheetReport.Cells[a, b].PutValue(valueOfTable, true, true); style.Font.IsBold = true; sheetReport.Cells[a, b].SetStyle(style); } // Set lại giá trị mặt định style.Font.IsBold = false; // Tăng cột theo dòng của table stepColumn++; } // Tăng dòng của table lên stepRow++; } } else { sheetReport.Cells["D10"].PutValue("Không có dữ liệu"); } //sheetReport.Cells.ConvertStringToNumericValue(); // Chạy process designer.Process(); switch (typeID) { // Theo ngày case "1": return(ExportReport("ReportDay", designer)); break; // Theo tháng case "2": return(ExportReport("ReportMonth", designer)); break; // Theo năm default: return(ExportReport("ReportYear", designer)); break; } }