简体   繁体   中英

Create Excel bar chart from a data source in C# code instead of a spreadsheet range using Aspose.Cells

I'm trying to use Aspose.Cells to generate a bar chart on a spreadsheet. The data source is an IEnumerable of decimal numbers, which are retrieved from a database. Reading the Aspose.Cells documentation, the only way I've seen to create a bar chart in code is by taking the bar chart's data from a range on a spreadsheet. I want to generate the chart directly from the IEnumerable, without having to actually include the data on a spreadsheet. Is there any way to do this, either using Aspose.Cells or standard .NET libraries? If it's possible to generate a temporary workbook in code, paste the data onto it and use that as a data source (discarding it immediately afterward), I could probably also make that work. Thanks!

Please see the following code. It creates the Bar Chart using Aspose.Cells APIs. Please read the comments inside the code for more help.

The following screenshot shows the output Excel file containing the Bar Chart generated by the code for your reference.

由Aspose.Cells生成的条形图


Sample Code in C#

// Create empty workbook.
Workbook wb = new Workbook();

// Access first worksheet.
Worksheet ws = wb.Worksheets[0];

// Add Bar chart in first worksheet.
int idx = ws.Charts.Add(ChartType.Bar, 5, 2, 20, 10);

// Access Bar chart.
Chart ch = ws.Charts[0];

// Add two number series, true means they are vertical.
ch.NSeries.Add("{6,3,1,7}", true);
ch.NSeries.Add("{2,5,7,1}", true);

// Set the category data to show on X-axis.
ch.NSeries.CategoryData = "{Apple,Pear,Orange,Mango}";

// Set the name of first and second series.
ch.NSeries[0].Name = "Cricket";
ch.NSeries[1].Name = "Hockey";

// Save the output in xlsx format.
wb.Save("outputBarChart.xlsx", SaveFormat.Xlsx);

Note: I am working as Developer Evangelist at Aspose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM