C# add simple title for spreadsheet chart OpenXml - c#

Hi!!
i'm able to write charts to my XLSX file. But i'm stuck adding a simple title for every chart. No styles just simple plain text.
My code is like this:
String Dtitulo = "Hello chart";
DocumentFormat.OpenXml.Drawing.Charts.Title chartTitle = new DocumentFormat.OpenXml.Drawing.Charts.Title();
chartTitle.ChartText = new ChartText();
chartTitle.ChartText.RichText = new RichText();
DocumentFormat.OpenXml.Drawing.Paragraph parrafoTitulo = new DocumentFormat.OpenXml.Drawing.Paragraph();
DocumentFormat.OpenXml.Drawing.Run run = parrafoTitulo.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text(Dtitulo));
chartTitle.ChartText.RichText.AppendChild<DocumentFormat.OpenXml.Drawing.Paragraph>(parrafoTitulo);
chart.Title = chartTitle;
But when i open my file with excel says "file is corrupt" or something like that.

A bit late but I was faced with the same task, and I created an excel sheet and added manually a chart with a chart title, then opened the xml to understand what tags were needed. And after a while I got it working. moved everything in a small function as below:
So you can provide your chart object and the title you want to the below function and it will add the chart title.
Note:Im using Open XML SDK 2.0 for Microsoft Office
private void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart,string title)
{
var ctitle = chart.AppendChild(new Title());
var chartText = ctitle.AppendChild(new ChartText());
var richText = chartText.AppendChild(new RichText());
var bodyPr = richText.AppendChild(new BodyProperties());
var lstStyle = richText.AppendChild(new ListStyle());
var paragraph = richText.AppendChild(new Paragraph());
var apPr = paragraph.AppendChild(new ParagraphProperties());
apPr.AppendChild(new DefaultRunProperties());
var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
}
And if you want a full example, you can review the official one here, and inject the above function in the right place (after the creation of the chart object) and it will add the chart title.

Related

ClosedXML Template not setting data into excel sheet

I am trying to put data into cells using closedxml and according to their site we have to set parameters like this on the cells {{TestName}} but it won't work for me.
This is my code and I am not sure where I am going wrong.
const string outputFile = #"\\Reports\Output\Test.xlsx";
var template = new XLTemplate(#"\\Reports\Test.xlsx");
var test = new models.Test();
test.id = 1;
test.TestName = "ASDF";
test.TestScore = "303";
template.AddVariable(test) //also tried doing it like this.
template.AddVariable("TestScore", "232");
template.AddVariable("TestName", "TESTNAME");
template.SaveAs(outputFile);
Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
And my excel template looks like this.
Solved it!
Just add template.Generate(); after adding the variables into the template.

Add date on Presentations (Open XML SDK) on C#

My reference is Presentations (Open XML SDK)
With the code-behind below I add the date on existing PowerPoint.
This code working and in the first slide the date is added, but it's possible customize the point on the page where to insert this date? The font and size ?
This is current output:
Thank you in advance for help.
string fileName = #"C:\\inetpub\\wwwroot\\aspnet\\Template\\01_FOCUS.pptx";
using (PresentationDocument oPDoc = PresentationDocument.Open(fileName, true))
{
PresentationPart oPPart = oPDoc.PresentationPart;
SlideIdList slideIdList = oPPart.Presentation.SlideIdList;
SlidePart sp = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => oPPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>().First();
AddDateToSlidePart(sp);
}
public static void AddDateToSlidePart(SlidePart slidePart1)
{
Slide slide1 = slidePart1.Slide;
CommonSlideData commonSlideData1 = slide1.GetFirstChild<CommonSlideData>();
ShapeTree shapeTree1 = commonSlideData1.GetFirstChild<ShapeTree>();
DocumentFormat.OpenXml.Presentation.Shape shape1 =
new DocumentFormat.OpenXml.Presentation.Shape();
DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties nonVisualShapeProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties();
DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties nonVisualDrawingProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() { Id = (UInt32Value)4U, Name = "Date Placeholder 3" };
DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties();
DocumentFormat.OpenXml.Drawing.ShapeLocks shapeLocks1 =
new DocumentFormat.OpenXml.Drawing.ShapeLocks() { NoGrouping = true };
nonVisualShapeDrawingProperties1.Append(shapeLocks1);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties1 =
new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape1 =
new PlaceholderShape() { Type = PlaceholderValues.DateAndTime, Size = PlaceholderSizeValues.Half, Index = (UInt32Value)10U };
applicationNonVisualDrawingProperties1.Append(placeholderShape1);
nonVisualShapeProperties1.Append(nonVisualDrawingProperties1);
nonVisualShapeProperties1.Append(nonVisualShapeDrawingProperties1);
nonVisualShapeProperties1.Append(applicationNonVisualDrawingProperties1);
DocumentFormat.OpenXml.Presentation.ShapeProperties shapeProperties1 =
new DocumentFormat.OpenXml.Presentation.ShapeProperties();
DocumentFormat.OpenXml.Presentation.TextBody textBody1 =
new DocumentFormat.OpenXml.Presentation.TextBody();
DocumentFormat.OpenXml.Drawing.BodyProperties bodyProperties1 =
new DocumentFormat.OpenXml.Drawing.BodyProperties();
DocumentFormat.OpenXml.Drawing.ListStyle listStyle1 =
new DocumentFormat.OpenXml.Drawing.ListStyle();
DocumentFormat.OpenXml.Drawing.Paragraph paragraph1 =
new DocumentFormat.OpenXml.Drawing.Paragraph();
DocumentFormat.OpenXml.Drawing.Field field1 =
new DocumentFormat.OpenXml.Drawing.Field() { Id = "{528B97E8-8E4B-4D32-BA17-4F287283DFD6}", Type = "datetime1" };
DocumentFormat.OpenXml.Drawing.RunProperties runProperties1 =
new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "it-IT" };
DocumentFormat.OpenXml.Drawing.Text text1 =
new DocumentFormat.OpenXml.Drawing.Text();
text1.Text = DateTime.Now.ToString("dd/mm/yyyy");
field1.Append(runProperties1);
field1.Append(text1);
DocumentFormat.OpenXml.Drawing.EndParagraphRunProperties endParagraphRunProperties1 =
new DocumentFormat.OpenXml.Drawing.EndParagraphRunProperties() { Language = "it-IT" };
paragraph1.Append(field1);
paragraph1.Append(endParagraphRunProperties1);
textBody1.Append(bodyProperties1);
textBody1.Append(listStyle1);
textBody1.Append(paragraph1);
shape1.Append(nonVisualShapeProperties1);
shape1.Append(shapeProperties1);
shape1.Append(textBody1);
shapeTree1.Append(shape1);
}
The OpenXML SDK Productivity tool (downloadable from the Microsoft site) is your friend here. When I need to do something like this, I:
Create the document I want
Open it in the appropriate tool (PowerPoint in this case).
Make a tiny change (to "dirty" the document and make PowerPoint believe it needs to be changed).
Save the result
Make the changes to the document that I want to see, and save the result with a new name
Open the OpenXML Productivity Tool and click the "Compare Files" tool.
The reason I force a save (in steps 3/4) is so that PowerPoint can add all of it's PowerPoint-ness to the document I created. The second save (step 5) will necessarily have all of that, so I want the two documents as close as possible - with only the "changes to the document that I want to see" being the difference between the two documents.
At this point, you should see a path to a solution to your problem. That tool is indispensable when working with OOXML.

How to dynamically add watermark to report in Stimulsoft

I would like to dynamically add watermark to a report that is generated in Stimulsoft. The watermark can not be hard-coded and only appear if the report was generated in TEST environment.
I have a variable that checks if the report was created in test environment:
isTestEnv
Which means that if the watermark was added to the page the old fashioned way I would use:
if(isTestEnv == true) {
Page1.Watermark.Enabled = true;
} else {
Page1.Watermark.Enabled = false;
}
But this is not the case. I have to add the watermark when generating the report. Does anyone know how to?
The text is same on all pages it simply says "TEST". But how to push that into a report is the mystery.
you can use this code and set your water mark image in your report
Stimulsoft.Base.StiLicense.loadFromFile("../license.key");
var options = new Stimulsoft.Viewer.StiViewerOptions({showTooltips:false});
var viewer = new Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);
var report = new Stimulsoft.Report.StiReport({isAsyncMode: true});
report.loadFile("Backgroundimg.mrt");
var page = report.pages.getByIndex(0);
page.watermark.image = Stimulsoft.System.Drawing.Image.fromFile('test.jpg');
page.watermark.aspectRatio = true;
page.watermark.imageStretch = true;
page.watermark.imageShowBehind= true;
report.renderAsync(function () {
viewer.report = report;
viewer.renderHtml("viewerContent");
});
You can set the report page watermark to some Report variable at design time and in your code set the value for the report variable.
Something like this:
StiReport report = new StiReport();
report.Load("REPORT_TEMPLATE_PATH");
//You can check if this variable exists or not using an if condition
report.Dictionary.Variables["WATERMARK_VARIABLE_NAME"] = "YOUR_TEXT";
report.Show();//or report.ShowWithWpf();

write to powerpoint pptx from c# using openxml

I am writing a data in to a pptx last slide using openxml in csharp and below is code to save the ppt
public static void CreateTableInLastSlide(PresentationDocument presentationDocument)
{
// Get the presentation Part of the presentation document
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Get the Slide Id collection of the presentation document
var slideIdList = presentationPart.Presentation.SlideIdList;
if (slideIdList == null)
{
throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
}
// Get all Slide Part of the presentation document
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presentationPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
// Get the last Slide Part of the presentation document
var tableSlidePart = (SlidePart)list.Last();
// Declare and instantiate the graphic Frame of the new slide
P.GraphicFrame graphicFrame = tableSlidePart.Slide.CommonSlideData.ShapeTree.AppendChild(new P.GraphicFrame());
ApplicationNonVisualDrawingPropertiesExtension applicationNonVisualDrawingPropertiesExtension = new ApplicationNonVisualDrawingPropertiesExtension();
P14.ModificationId modificationId1 = new P14.ModificationId() { Val = 3229994563U };
modificationId1.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
applicationNonVisualDrawingPropertiesExtension.Append(modificationId1);
graphicFrame.NonVisualGraphicFrameProperties = new DocumentFormat.OpenXml.Presentation.NonVisualGraphicFrameProperties
(new A.NonVisualDrawingProperties() { Id = 5, Name = "table 1" },
new A.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new ApplicationNonVisualDrawingPropertiesExtensionList(applicationNonVisualDrawingPropertiesExtension)));
graphicFrame.Transform = new Transform(new Offset() { X = 10, Y = 10 });
graphicFrame.Graphic = new A.Graphic(new A.GraphicData(GenerateTable()) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" });
presentationPart.Presentation.Save();
}
the file is saved with required data but
While opening the powerpoint I get the following error:
Powerpoint found a problem with content in "Sample.pptx". Power point can attempt to repair the presentation.
Once repaired, the content is shown ok. but since the file is corrupted when i run the code it is not updating with the latest data nexttime.
Please help me to solve the issue
-tried to open in different version of office but no luck
-created the template from different versions still the issue occurs

Creating statecharts in Visio using c#

Can anyone point me to an example of how to programatically create a statechart in visio?
I can create blank pages, drop shapes, open template etc, but when I try to add transitions it complains that the page is not the right type.
Can't find a sample anywhere.
Alternatively: I can save the user actions to create the chart as a macro. Can I run that programatically?
Thanks.
< edit >
Step away from the PC for 2 minutes and you realise you should have put the code snippet in the question and not try to put it in comments. Forest: meet trees...
Visio.Document umlStencil = visioApp.Documents.OpenEx(#"UMLSTA_M.vss", (short)VisOpenSaveArgs.visOpenDocked);
Visio.Page page = visioDoc.Pages.Add();
Visio.Shape s1 = page.Drop(umlStencil[#"State"], 5.0, 5.0);
Visio.Shape s2 = page.Drop(umlStencil[#"State"], 5.0, 5.0);
Visio.Shape transition = page.Drop(umlStencil[#"Transition"], 1.0, 1.0);
As you can see, pretty similar to the snippet in the answer below.
< / edit >
This is the code that I ran with Visual Studio 2010 against both Visio 2007 and Visio 2010.
var visioApp = new Visio.Application();
// Load the UML Statechart stencil (docked)
var stencil_open_flags = Visio.VisOpenSaveArgs.visOpenDocked;
var umlStencil = visioApp.Documents.OpenEx(#"UMLSTA_M.vss", (short)stencil_open_flags);
// create a new empty doc based on the UML Model Template
var doc = visioApp.Documents.AddEx("UMLMOD_U.VST", Visio.VisMeasurementSystem.visMSUS, 0, 0);
var page = doc.Pages.Add();
// Find and manually change the diagram's title
var watermark = page.Shapes["Watermark Title"];
var LockTextEdit_cell = watermark.CellsU["LockTextEdit"];
LockTextEdit_cell.FormulaForceU = "GUARD(0)";
watermark.Text = "MyTitle";
LockTextEdit_cell.FormulaForceU = "GUARD(1)";
// Find the masters we need
var state_master = umlStencil.Masters["State"];
var transition_master = umlStencil.Masters["Transition"];
// Drop the masters into the page
var s1 = page.Drop(state_master, 5.0, 5.0);
var s2 = page.Drop(state_master, 1.0, 1.0);
var transition = page.Drop(transition_master, 3.0, 3.0);

Categories