5

How to create charts in excel,While exporting data from database to excel sheet..!

I'm exporting data to excel from database.I need to create chart in the excel sheet based on data from database. Below code creates simple excel sheet I need to make changes in the same code to create charts. Please Guide

    public ActionResult ExportToExcel()
    {

            var workbook = new ClosedXML.Excel.XLWorkbook();
            var worksheet = workbook.Worksheets.Add("SheetOne");
            DocumentFormat.OpenXml.Drawing.PictureLocks piclocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
            worksheet.Cell("A1").Value = "Test data!";
            Response.ClearContent();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;filename=\"SheetOne.xlsx\"");
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
           workbook.SaveAs(memoryStream);
            memoryStream.WriteTo(Response.OutputStream);
            memoryStream.Close();
            Response.End();
            return File(memoryStream, "application/ms-excel", "PPs_Workflow.xlsx");

    } *
Vahid Farahmandian
  • 6,081
  • 7
  • 42
  • 62
Junaid
  • 51
  • 1
  • 1
  • 5

3 Answers3

6

Unfortunately, to my knowledge, ClosedXML doesn't support adding charts.

So in order to accomplish what you need, you'll need to create an Excel file (to use as a template) and add the chart(s) you need manually. After that, you can use ClosedXML to open and edit the existing file (as opposed to creating a new file as you're currently doing). When the data updates, the chart will automatically update along with it.

dhughes
  • 295
  • 5
  • 10
3

You can use OfficeOpenXml, Here you can get a wide variety of charts with some flexible options

*ExcelChart chart = chartSheet.Drawings.AddChart("MyChart",
OfficeOpenXml.Drawing.Chart.eChartType.ColumnClustered);
chart.Title.Text = "Category Chart";
chart.SetPosition(1, 0, 3, 0);
chart.SetSize(800, 300);
var ser1 = (ExcelChartSerie)(chart.Series.Add(workSheet.Cells["B2:B6"],
workSheet.Cells["A2:A6"]));*
3

Although ClosedXML may not support charting, OpenXML does. Since ClosedXML is a simplified interface to OpenXML, there is no reason that I can see that you cannot mix them. (You automatically get an OpenXML reference when you pull ClosedXML from nuget). Like everything in OpenXML, it is kind of ugly. (That is why ClosedXML is so popular)

I found some examples of using OpenXML at https://csharp.hotexamples.com/examples/DocumentFormat.OpenXml.Drawing.Charts/PieChart/-/php-piechart-class-examples.html

Mark Ainsworth
  • 811
  • 8
  • 24