توليد تقارير إكسل المنسقة بشكل ديناميكي مع رسم بياني أنيق

نظرة عامة

هناك سيناريوهات ويب معينة تتطلب كل من التقارير والعروض التقديمية ، مزيج من الأجزاء أو الكائنات التي يمكن أن تعمل معًا بشكل جيد. يشرح المقال كم من السهل تصميم وإنشاء تقارير إكسل أنيقة بشكل ديناميكي بطريقة وضوح المخرج. يقوم بتصدير البيانات من ملف XML (يمكنك أيضًا استخدام مصادر بيانات أخرى) إلى عنصر تحكم Aspose.Cells.GridWeb الذي يوفر لك البيئة الحقيقية التي تتيح لك تطبيق تنسيق غني وجذاب على البيانات وحساب النتائج المتعلقة بالصيغة مثل MS Excel. كما يقوم بإنشاء رسم بياني معقد استنادًا إلى بيانات مصدر صفحة العمل باستخدام Aspose.Cells ويرقق صورة الرسم البياني في تقرير المبيعات. في النهاية ، يتم حفظ التقرير إكسل مع الرسم البياني المرفق إلى القرص باستخدام عنصر تحكم Aspose.Cells.

يتضمن هذا المقال رمز المصدر ومشروع العرض التوضيحي بالكامل لمثل هذه الوظيفة.

يتيح للمستخدمين إدراك مفصل حول كيفية إنشاء تقرير تجاري لإدخال البيانات في صفحة عمل الشبكة وتطبيق بعض التنسيق على الخلايا في الصفوف والأعمدة ، تضمين رسم بياني استنادًا إلى نطاق البيانات المصدرية قبل حفظ تقرير إكسل على القرص.

مكونات Aspose

أستخدم ثلاثة من أسبوس‘s المكونات لأداء المهمة بسهولة. أسبوس ، الناشر المكونات .NET وجافا ، يوفر مجموعة متنوعة من المكونات ثرية الميزات. أسبوس يوفر مجموعة كبيرة من المكونات .NET وجافا. يثق الآلاف من العملاء في جميع أنحاء العالم في المنتجات التي تشمل مكونات تنسيق الملفات ، منتجات التقارير ، ومكونات الرؤية ومكونات الأدوات التي تسمح بفتح الوثائق ، تعديلها ، إنشاؤها ، حفظها ، دمجها ، تحويلها إلى الخ وثائق في مختلف الأشكال بما في ذلك DOC ، RTF ، WordML ، HTML ، PDF ، XLS ، SpreadsheetML ، محددة بعلامة تبويب ، CSV ، PPT ، SWF ، EMF ، WMF ، MPX ، MPD وأشكال أخرى.

أود أن أستغل هذه الفرصة لتقديم ثلاثة من هذه المكونات إليك التي تم استخدامها في هذه المهمة.

عناصر التحكم Grid Aspose.Cells

عناصر التحكم Grid Aspose.Cells هي حلاً شاملاً للشبكة. تأتي عناصر التحكم Grid Aspose.Cells مع عنصري واجهة المستخدم GUI .NET المختلفين (Aspose.Cells.GridDesktop وAspose.Cells.GridWeb): أحدهما لدعم التطبيقات سطح المكتب والآخر لدعم تطبيقات الويب. كلا الإصدارين متطابقين بالتساوي لجعل التنفيذ في أي منصة أمرًا سهلاً. يوفر Aspose.Cells.GridWeb القدرة على الاستيراد من وتصدير إلى جداول بيانات Excel. لذا يمكن لأي شخص ملم بـ Excel (حتى المستخدمون النهائيون) تصميم المظهر والشعور بالشبكة. تقدم Aspose.Cells.GridWeb أيضًا واجهة برمجية سهلة الاستخدام وغنية الميزات توفر للمطورين التحكم الكامل في المظهر والشعور وسلوك شبكتهم. لمعرفة المزيد حول المنتج وميزاته ودليل المبرمجين ، يرجى التحقق من ملخص قائمة الميزات ووثائق Aspose.Cells.GridWeb وعروض الـإسعار عبر الإنترنت

Aspose.Cells

Aspose.Cells هو مكون تقرير جدول بيانات Excel يتيح لك قراءة وكتابة جداول بيانات Excel دون الحاجة لتثبيت Microsoft Excel سواء على الجانب العميل أو الخادم. Aspose.Cells هو مكون غني بالميزات يقدم الكثير أكثر من مجرد تصدير البيانات الأساسية. باستخدام Aspose.Cells يمكن للمطورين تصدير البيانات، تنسيق الجداول بكل تفصيل وعلى كل مستوى، استيراد الصور، استيراد الرسوم البيانية، إنشاء رسوم بيانية، تلاعب بالرسوم البيانية، تدفق بيانات Excel، حفظ في تنسيقات متعددة بما في ذلك XLS و CSV وSpreadsheetML وTabDelimited وTXT وXML (مدمج مع Aspose.Pdf) والكثير من التنسيقات الأخرى. Aspose.Cells يقدم واجهة برمجة تطبيقات سهلة الاستخدام وغنية بالميزات للمبرمجين. يحتوي على قائمة ضخمة من الميزات. لمعرفة المزيد حول المنتج وميزاته ودليل المبرمج، يرجى التحقق من ملخص قائمة الميزات، توثيق Aspose.Cells وعروض الأدوات عبر الإنترنت. يمكنك تنزيل الإصدار التجريبي مجانًا.

تصميم الواجهة

نبدأ في إنشاء تطبيق ويب جديد لـ Asp.Net في Visual Studio.Net.

أضيف الإشارة إلى ثلاث مكونات، أي Aspose.Cells.GridWeb.dll، Aspose.Chart.dll و Aspose.Cells.dll إلى المشروع أولاً. أضع بعض ال contorl على الصفحة وأضبط خصائصها، أضع مكون Aspose.Cells.GridWeb (GridWeb) عليها من شريط الأدوات. بعد إضافة الإشارات إلى الثلاث مكونات، يظهر مكون GridWeb على شريط الأدوات. المكونان الآخران (Aspose.Chart و Aspose.Cells) هما مكتبات فقط، يتم الإشارة إليهما فقط.

أنشئ أيضًا مجلدين “file” و “images”، وأضف “Products.xml” و “chart.gif” إلى هذين المجلدين على التوالي. يعد ملف XML ملف مصدر البيانات الذي سيتم استخراج البيانات منه لملء ورقة العمل GridWeb. يوفر ملف الصورة صورة لزر مخصص يتم وضعه على مكون GridWeb.

الآن، أنشئ زر أمر مخصص. ببساطة أنقر بزر الماوس الأيمن على مكون GridWeb وانقر على “أزرار الأوامر المخصصة…”.

سيقوم ذلك بتفعيل محرر الأزرار المخصصة، ويسمح لك المحرر بإنشاء أزرار صور الأوامر المخصصة مع تلميح الأداة المرفق. أحدد القيم لبعض خصائص الزر مثل الأمر (الاسم) -> “btnChart”، ImageUrl -> أعط المسار إلى ملف الصورة (“chart.gif”) و ToolTip -> أعط تلميح الأداة.

لذا، تمت إضافة الزر لأمر مخصص كما يمكنك رؤيته (محاط بلون أحمر) في لقطة الشاشة التالية.

todo:image_alt_text

أخيرًا، أضبط بعض خصائص الخط (سميك) للتسمية والزر الأمر. كما أقوم بضبط حجم العناصر التحكمية للحصول على النظرة النهائية.

todo:image_alt_text

استرجاع البيانات من ملف XML

فيما يلي هيكل ملف XML المستخدم في المشروع.

هيكل ملف XML

XML

 <?xml version="1.0" standalone="yes"?>

<SalesData>

  <Products>

    <ProductName>Data</ProductName>

    <QuantityPerUnit>Data</QuantityPerUnit>

    <CategoryName>Data</CategoryName>

    <UnitPrice>Data</UnitPrice>

    <Sale>Data</Sale>

  </Products>

 .........

</SalesData>
 private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

{

	// Uncomment the code below when you have purchased license

	// for Aspose.Cells.GridWeb, Aspose.Chart and Aspose.Cells. You need

	// to deploy the licenses in the same folder as your executable,

      // alternatively you can add the license files as an embedded

      // resource to your project.

	//

	// Set the license for Aspose.Cells.GridWeb

	// Aspose.Cells.GridWeb.License gridwebLicense = new

	// Aspose.Cells.GridWeb.License();

	// gridwebLicense.SetLicense("Aspose.Grid.lic");

	//

	// // Set the license for Aspose.Chart

	// Aspose.Chart.License chartLicense = new

	// Aspose.Chart.License();

	// chartLicense.SetLicense("Aspose.Chart.lic");

	//

	// // Set the license for Aspose.Cells

	// Aspose.Cells.License cellsLicense = new

	// Aspose.Cells.License();

	// cellsLicense.SetLicense("Aspose.Cells.lic");

	//Create a DataSet object.

	DataSet ds = new DataSet();

	//Get the Virtual Folder Path.

	string path = MapPath(".");

	//Reads XML data from xml file into DataSet object.

	ds.ReadXml(path + "\\file\\Products.xml");

	//Call the custom method to obtain distinct values from

	//CategoryName field and store data into an object array.

	object [] drs = GetDistinctValues(ds.Tables[0],"CategoryName");

	//Fill the drop down list with distinct field items.

	for(int i = 0;i<drs.Length;i++)

	{

		DropDownList1.Items.Add(drs[i].ToString());

	}

}

}

//This method is used to filter distinct values from CategoryName field in the datatable.

private object[] GetDistinctValues(DataTable dtable, string colName)

{

	// Create a Hashtable object.

	Hashtable hTable = new Hashtable();

	// Loop through the datatable rows and add distinct values to

	// Hashtable object minimizing the duplicates in the field.

	foreach (DataRow drow in dtable.Rows)

	if(!hTable.ContainsKey(drow[colName]))

	hTable.Add(drow[colName], string.Empty);

	// Create an object array based on the distinct key values of the Hashtable object.

	object[] objArray = new object[hTable.Keys.Count];

	// Copy the disctinct values to fill the array.

	hTable.Keys.CopyTo(objArray, 0);

	// Return the array object.

	return objArray;

}

ملء ورقة العمل لتحكم Aspose.Cells.GridWeb بالبيانات

أستخدم بعض واجهة برمجة التطبيقات لتحكم GridWeb لملء ورقة عمل بالبيانات من ملف XML المصدر. أكتب الكود في معالج حدث النقر على زر الأمر (المسمى “إظهار التقرير”). يتم تصفية تقرير البيانات استنادًا إلى العنصر المحدد من قائمة القائمة المنسدلة.

 //Clears datasheets of the GridWeb control.

GridWeb1.WebWorksheets.Clear();

//Create a DataSet object.

DataSet ds = new DataSet();

//Get the Virtual Folder path.

string path = MapPath(".");

//Reads XML data from xml file into DataSet object.

ds.ReadXml(path + "\\file\\Products.xml");

//Create a DataView based on the datatable.

DataView dv = new DataView(ds.Tables[0]);

//Filter data in the DataView object based on the selected drop down list item.

dv.RowFilter = "CategoryName ='" + DropDownList1.SelectedItem.Text + "'";

//Importing data from the filtered DataView object to create and

//fill "Products" Worksheet start from A4 cell.

GridWeb1.WebWorksheets.ImportDataView(dv, null, null,"Products",3,0);

تنسيق البيانات في الخلايا

لتمييز بين مختلف أنواع المعلومات على ورقة عمل، لعرض البيانات بشكل أمثل على ورقة العمل وجعلها أسهل في المسح، تقوم بتنسيق الورقة. يمثل Format نمطًا ويعرف على أنه مجموعة من الخصائص مثل الخطوط وأحجام الخطوط وتنسيقات الأرقام وحدود الخلية والتظليل بألوان خلفية ثابتة أو نمط لون محدد، المسافة المتقدمة والتوجيه النصي في الخلايا.

أدمج بعض السطور الإضافية من الكود السابق. أضع عنوان / عنوان فرعي للتقرير، وأقوم بتنسيق العنوان والعنوان الفرعي والخلايا التفصيلية. كما أقوم بتطبيق تنسيق الأرقام على الحقول المختلفة (ضبط تنسيق العملة لحقول سعر الوحدة والمبيعات) وضبط ارتفاع/عرض الصفوف والأعمدة باستخدام واجهة برمجة التطبيقات Aspose.Cells.GridWeb.

 //Create the title cell (A1) in the sheet and apply formattings.

//The following lines input a string value to the cell, specify

//font size, specify horizontal and vertical align settings, set

//foreground and background colors and merge cells (A1:E2).

WebWorksheet sheet = GridWeb1.WebWorksheets[0];

sheet.Cells["A1"].PutValue("Product Sales By Category");

sheet.Cells["A1"].Style.Font.Size = new FontUnit("20pt");

sheet.Cells["A1"].Style.HorizontalAlign = HorizontalAlign.Center;

sheet.Cells["A1"].Style.VerticalAlign = VerticalAlign.Middle;

sheet.Cells["A1"].Style.BackColor = Color.SkyBlue;

sheet.Cells["A1"].Style.ForeColor = Color.Blue;

sheet.Cells.Merge(0, 0, 2, 5);

//Create the subtitle cell (A3) in the sheet and apply formattings.

//The following lines input a string value to the cell, specify

//font size with attributes, specify horizontal and vertical align

//settings, set foreground and background colors and merge cells

//(A3:E3).

sheet.Cells["A3"].PutValue(DropDownList1.SelectedItem.Text);

sheet.Cells["A3"].Style.Font.Size = new FontUnit("13pt");

sheet.Cells["A3"].Style.Font.Bold = true;

sheet.Cells["A3"].Style.Font.Italic = true;

sheet.Cells["A3"].Style.HorizontalAlign = HorizontalAlign.Left;

sheet.Cells["A3"].Style.VerticalAlign = VerticalAlign.Middle;

sheet.Cells["A3"].Style.BackColor = Color.SeaGreen;

sheet.Cells["A3"].Style.ForeColor = Color.Yellow;

sheet.Cells.Merge(2, 0, 1, 5);

//Obtain the last row and column (which contain data) indexes.

int totalrow = sheet.Cells.MaxRow +1;

int totalcol = sheet.Cells.MaxColumn;

//Get the sheet Cells collections

WebCells cells = sheet.Cells;

//Define the Cell object.

WebCell cell;

//Loop through the data in the sheet and format two fields with

//Currency number style.

for (int i = 4;i<=totalrow;i++)

{

	//Format the Sale Column.

	cell = cells[i,totalcol];

	cell.PutValue(cell.StringValue,true);

	cell.NumberType = NumberType.Currency1;

	//Format the UnitPrice Column.

	cell = cells[i,totalcol-1];

	cell.PutValue(cell.StringValue,true);

	cell.NumberType = NumberType.Currency1;

}

//Insert the Total row with data, formula and formatting style.

//It will calculate the total Sales of a Category.

cells[totalrow,0].PutValue( DropDownList1.SelectedItem.Text + " Total" );

cells[totalrow,0].Style.Font.Bold = true;

cells[totalrow,totalcol].Formula = "=SUM(E5:E" + totalrow.ToString() + ")";

cells[totalrow,totalcol].Style.Font.Bold = true;

//Specify some Row and Column formattings. It will set row height

//and column width accordingly.

cells.SetRowHeight(2, new Unit("17pt"));

cells.SetColumnWidth(0, new Unit("157pt"));

cells.SetColumnWidth(1, new Unit("106pt"));

cells.SetColumnWidth(2, new Unit("87pt"));

cells.SetColumnWidth(3, new Unit("56pt"));

cells.SetColumnWidth(4, new Unit("50pt"));

إنتاج تقرير مهيأ (.XLS File) مع رسم بياني باستخدام مكون Aspose.Cells

الآن، سأكتب بعض الشفرة لحفظ التقرير المنسق مع الرسم البياني في القرص. أستخدم زر حفظ GridWeb، يتم تنشيط حدث SaveCommand لـ GridWeb عند النقر فوق زر الحفظ، لذلك، سأتعامل مع ذلك. هنا، استخدم مكون Aspose.Cells لتصدير التقرير المنسق إلى MS Excel، وتوليد الرسم البياني وتضمينه في ملف الإكسل الناتج. لم أقم بإدراج صورة الرسم البياني (التي تم إنشاؤها بواسطة المكون Aspose.Chart) بل قمت بإنشاء الرسم البياني المماثل باستخدام واجهة برمجة التطبيقات لـ Aspose.Cells حتى تتمكن من تحرير الرسم البياني في MS Excel وفقًا لاحتياجاتك.

 //This GridWeb control event is fired when you click on the "Save" button

//of the control. After Clicking this button "File Download" dialog is

//displayed and you may open into MS Excel / save the output excel file //with graph to disk.

private void GridWeb1_SaveCommand(object sender, System.EventArgs e)

{

	//Create MemoryStream object.

	System.IO.MemoryStream ms = new System.IO.MemoryStream();

	//Save the GridWeb's Report to the stream.

	this.GridWeb1.WebWorksheets.SaveToExcelFile(ms);

	//Create a new Workbook.

	Workbook workbook = new Workbook();

	//Open the stream into the Workbook.

	workbook.Open(ms);

	//Call the custom method which creates Chart.

	Workbook book = CellsChart(workbook);

	//Save the excel file displaying "File Download" dialog box.

	book.Save(ms, FileFormatType.Default);

	this.Response.ContentType = "application/vnd.ms-excel";

	this.Response.AddHeader("content-disposition", "attachment; filename=Export.xls");

	this.Response.BinaryWrite(ms.ToArray());

}

//This custom method is used to create the Chart based on the data source

//range in the GridWeb control. In this method we will use Aspose.Cells

//APIs to create the graph which will be saved later into the output //excel file.

private Workbook CellsChart(Workbook workbook)

{

	//Get the first Worksheet.

	Aspose.Cells.Worksheet sheet = workbook.Worksheets[0];

	//Get the Cells collection in the sheet.

	Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;

	//Get the last row index.

	int maxrow = sheet.Cells.MaxDataRow;

	//Unmerge the cells.

	sheet.Cells.UnMerge(maxrow,0,15,10);

	int chartIndex = 0;

	//Add a new Chart into the sheet's Chart Collection.

chartIndex = sheet.Charts.Add(Aspose.Cells.ChartType.Pie,maxrow,0,maxrow+28,5);

	//Get the Chart object.

	Aspose.Cells.Chart chart = sheet.Charts[chartIndex];

	//Set the Chart Area.

	Aspose.Cells.ChartArea chartarea = chart.ChartArea;

	chartarea.Area.Formatting = FormattingType.Custom;

	chartarea.Border.IsVisible = false;

		chartarea.Area.FillFormat.SetTwoColorGradient(Color.PowderBlue, Color.LightSkyBlue, GradientStyleType.FromCenter,1);

	//Set some properties of Chart Plot Area.

	chart.PlotArea.Area.Formatting = FormattingType.None;

	chart.PlotArea.Border.IsVisible = false;

	//Set properties of Chart Title.

	chart.Title.Text = DropDownList1.SelectedItem.Text + " Sales";

	chart.Title.TextFont.Size = 20;

	//Set properties of NSeries

	int lastdatarow = maxrow-1;

	chart.NSeries.Add("E5:E" + lastdatarow.ToString(), true);

	chart.NSeries.CategoryData = "A5:A" + lastdatarow.ToString();

	//Set the Data Labels in the chart

	Aspose.Cells.DataLabels datalabels;

	for ( int i = 0; i < chart.NSeries.Count ;i ++ )

	{

		datalabels = chart.NSeries[i].DataLabels;

		datalabels.Postion = Aspose.Cells.LabelPositionType.Center;

		datalabels.IsPercentageShown = true;

	}

	//Set the Legend settings.

	Aspose.Cells.Legend legend = chart.Legend;

	legend.Position = Aspose.Cells.LegendPositionType.Bottom;

	legend.Height = 85;

	legend.Width = 330;

	legend.AutoScaleFont = true;

	legend.Border.Color = Color.Blue;

	legend.Area.Formatting = FormattingType.Custom;

	FillFormat fillformat = legend.Area.FillFormat;

	legend.Area.Formatting = FormattingType.None;

	legend.Border.IsVisible = false;

	//Autofit the first column.

	sheet.AutoFitColumn(0);

	//Return the Workbook.

	return workbook;

}

تشغيل التطبيق

الآن، أقوم بتشغيل التطبيق. قائمة السقط ممتلئة بالفئات المميزة.

todo:image_alt_text

أختار فئة أريد عرض تقرير المبيعات بناءً عليها وأنقر على زر “عرض التقرير”.

todo:image_alt_text

لذا، يتم عرض التقرير في GridWeb استنادًا إلى الفئة المحددة. يتم تنسيق التقرير افتراضيًا استنادًا إلى الشفرة (المكتوبة سابقًا).

todo:image_alt_text

إذا كنت ترغب في تنسيق البيانات في بعض الخلايا بطريقة WYSIWYG، فيمكنك القيام بذلك بسهولة. يوفر Aspose.Cells.GridWeb محرر Format Cells، حدد الخلية (الخلايا) المطلوبة وانقر بزر الماوس الأيمن فوقها، ثم انقر على خيار “تنسيق الخلية…”.

todo:image_alt_text

يتم عرض مربع حوار Format Cell.

todo:image_alt_text

أحدد بعض السمات الخط وأنقر على موافق.

todo:image_alt_text

وأحصل على النتيجة.

todo:image_alt_text

بالإضافة إلى تنسيق الخلايا، يمكنك أيضًا تحرير قيم الخلية الخاصة بك. انقر مرتين فوق الخلية (الخلايا) المرغوبة لديك وقم بتحرير القيمة.

todo:image_alt_text

لتقديم نتيجة التحرير وإعادة حساب جميع الصيغ، أنقر فوق الزر ذو اللون الأحمر المحاط به لتحديث التقرير.

todo:image_alt_text

الآن سأقوم بإنشاء الرسم البياني ولصقه في العنصر التحكم. أنقر على الزر الأمر المخصص (المحاط بلون أحمر) لإنشاء الرسم الدائري بناءً على نطاق البيانات.

todo:image_alt_text

وأخيرًا، سأقوم بتصدير هذا التقرير مع الرسم البياني إلى MS Excel. أنقر على زر الحفظ (المحاط بلون أحمر). بالنقر على الزر حفظ سيتم عرض مربع الحوار “تنزيل الملف”، يمكنك إما فتح التقرير الناتج (ملف إكسل الناتج مع الرسم البياني) في MS Excel أو حفظه على القرص.

todo:image_alt_text

عند النقر على زر فتح (مربع حوار تنزيل الملف)، يتم تصدير تقرير الإكسل مع الرسم البياني إلى MS Excel ويتم عرض الجزء العلوي من التقرير.

todo:image_alt_text

يتم عرض الجزء السفلي من تقرير الإكسل.

todo:image_alt_text