简体   繁体   中英

How to add to Text Label For excel Charts using Open xml or EPPLUS

I am completely new to Excel automation in C#

Actually I am came across some of API for Excel generation in C# .net like CLOSED XML , EEPLUS , and spreadsheetlight by vincent ,Open XML by Microsoft , Interop excel by Microsoft

According My Study

CLOSED XML -- No charts supported

EEPLUS - Charts supported

Spread light- Very easy to use and Charts also supported

Open XML- complex hard to work

I was completely fine with Spread light light was good API , but i am not able to find a solution how to add label inside a Chart

I hope any one in stack overflow came across with same problem.

I need to add label like text inside chart like for example Company in chart.

Please let me know how to find solution any one this Free API

请在这里找到图表信息

Thanks
Ranjith

You can add at title via Epplus but positioning will require XML editing:

    [TestMethod]
    public void Chart_Manual_Title_Test()
    {
        //http://stackoverflow.com/questions/37304860/how-to-add-to-text-label-for-excel-charts-using-open-xml-or-epplus
        //Throw in some data
        var datatable = new DataTable("tblData");
        datatable.Columns.AddRange(new[] { new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(object)) });

        for (var i = 0; i < 10; i++)
        {
            var row = datatable.NewRow();
            row[0] = i;
            row[1] = i * 10;
            row[2] = Path.GetRandomFileName();
            datatable.Rows.Add(row);
        }

        //Create a test file    
        var fileInfo = new FileInfo(@"c:\temp\Chart_Manual_Title_Test.xlsx");
        if (fileInfo.Exists)
            fileInfo.Delete();

        using (var pck = new ExcelPackage(fileInfo))
        {
            var workbook = pck.Workbook;
            var worksheet = workbook.Worksheets.Add("Sheet1");
            worksheet.Cells.LoadFromDataTable(datatable, true);

            var chart = worksheet.Drawings.AddChart("chart test", eChartType.XYScatter);
            var series = chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);

            chart.Title.Text = "XYZ Corp";

            //Add custom layout
            var chartXml = chart.ChartXml;
            var nsm = new XmlNamespaceManager(chartXml.NameTable);

            var nsuri = chartXml.DocumentElement.NamespaceURI;
            nsm.AddNamespace("c", nsuri);
            nsm.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            //Set the title overlay
            var overlayNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:title/c:overlay", nsm);
            overlayNode.Attributes["val"].Value = "1";

            //Set the font size
            var defRPrNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:title/c:tx/c:rich/a:p/a:pPr/a:defRPr", nsm);
            defRPrNode.Attributes["sz"].Value = "1200";

            //Get the title layout and add the manual section
            var layoutNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:title/c:layout", nsm);
            var manualLayoutNode = chartXml.CreateElement("c:manualLayout", nsuri);
            layoutNode.AppendChild(manualLayoutNode);

            //Add coordinates
            var xModeNode = chartXml.CreateElement("c:xMode", nsuri);
            var attrib = chartXml.CreateAttribute("val");
            attrib.Value = "edge";
            xModeNode.Attributes.Append(attrib);
            manualLayoutNode.AppendChild(xModeNode);

            var yModeNode = chartXml.CreateElement("c:yMode", nsuri);
            attrib = chartXml.CreateAttribute("val");
            attrib.Value = "edge";
            yModeNode.Attributes.Append(attrib);
            manualLayoutNode.AppendChild(yModeNode);

            var xNode = chartXml.CreateElement("c:x", nsuri);
            attrib = chartXml.CreateAttribute("val");
            attrib.Value = "0.9";
            xNode.Attributes.Append(attrib);
            manualLayoutNode.AppendChild(xNode);

            var yNode = chartXml.CreateElement("c:y", nsuri);
            attrib = chartXml.CreateAttribute("val");
            attrib.Value = "0.95";
            yNode.Attributes.Append(attrib);
            manualLayoutNode.AppendChild(yNode);

            pck.Save();
        }
    }

Which gives you this in the output:

在此处输入图片说明


RESPONSE TO COMMENTS

Ok, thats a little tougher. The right way would be to use a relSizeAnchor which can be placed inside the chart and moved/sized with it. But that you would have to do from scratch (or at best another library). If you activate a chart in excel and do an Insert > Text Box to see what that looks like.

Another option would be to fake it by using an unused title like say an Axis Title and moving it similar to how I did the chart title.

But the easiest option would be to simply add a shape. The draw back is if you move the chart it will not move with it:

var tb1 = worksheet.Drawings.AddShape("tb1", eShapeStyle.Rect);
tb1.Text = "ABC Company";
tb1.SetPosition(1, 0, 2, 0);
tb1.SetSize(200, 20);
tb1.Font.Color = Color.Black;
tb1.TextAlignment = eTextAlignment.Center;
tb1.Fill.Color = Color.LightYellow;
tb1.Fill.Style = eFillStyle.SolidFill;
tb1.Border.Fill.Color = Color.Red;

gives this as the output when combined with above:

在此处输入图片说明

Essential XlsIO can add textboxes to Excel charts.

Example code

//Accessing the chart of the worksheet IChartShape shape = workbook.Worksheets[0].Charts[0]; //Adding textbox to chart shape shape.TextBoxes.AddTextBox(1,1, 100,200); //Setting position for textbox shape.TextBoxes[0].Top = 900; shape.TextBoxes[0].Left = 750; //Adding text to textbox shape.TextBoxes[0].Text = "New textbox";

The whole suite of controls is available for free (commercial applications also) through the community license program if you qualify (less than 1 million US Dollars in revenue). The community license is the full product with no limitations or watermarks.

Note: I work for Syncfusion.

在此处输入图片说明

If the chart already exists in your template and you are just adding data, then you can read the contents of the box from a cell on the page. Then from C# you just need to write to the cell. This lets you do any formatting or positioning you want in Excel.

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