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.
Related
I'm moving some legacy code using Office Interop libraries to epplus, one thing I can't figure out is how to set a Workbook to ask the user on open the file to open it read only. Like if the user clicks on File -> Info -> Protect Workbook -> Always Open Read-Only
I've tried to set the DocSecurity property stated here (https://sno.phy.queensu.ca/~phil/exiftool/TagNames/OOXML.html), but to no success. excelWorkBook.Properties.SetExtendedPropertyValue("DocSecurity", "2");
I also tried to add the following node to the workbookxml <fileSharing readOnlyRecommended="1"/>
I even tried to compare the unzipped excel files protected, non protected, but there were too many changes.
It can be done but it is not really straightforward. Setting DocSecurity can be done by generating the Workbook.Properties object. But that is only half of it. You also need to set the flag inside the Workbook itself which can only be done via XML manipulation.
[TestMethod]
public void DocSecurity_Test()
{
//https://stackoverflow.com/questions/58335624/is-there-a-programmatically-way-for-excels-protect-workbook
var fi = new FileInfo(#"c:\temp\DocSecurity_Test.xlsx");
if (fi.Exists)
fi.Delete();
using (var package = new ExcelPackage(fi))
{
//Create a simple workbook
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].Value = "Test";
//Extended properties is a singleton so reference it to generate the app.xml file
//needed and add the security setting
var extProps = workbook.Properties;
extProps.SetExtendedPropertyValue("DocSecurity", "2");
//Also need to tell the workbook itself but can only do it via XML
var xml = workbook.WorkbookXml;
var att = xml.CreateAttribute("readOnlyRecommended");
att.Value = "1";
const string mainNs = #"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var fileSharing = xml.CreateElement("fileSharing", mainNs);
fileSharing.Attributes.Append(att);
//Element must be at the beginning of the tree
xml.DocumentElement.PrependChild(fileSharing);
package.Save();
}
}
Which will look like this:
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();
I am trying to write code which produces excel report with pivot table. For accomplishing this task I am using ClosedXML library. The output looks like this:
The problem is that I have to get all groups of data collapsed by default, i.e. in the output I should see the following:
In other words, my output should contain collapsed rows and only summary should be displayed. How can I achieve this in code? Which method should I use?
pt.ShowRowStripes = true;
secondWorksheet.FirstRow().Hide();
secondWorksheet.TabActive = true;
secondWorksheet.CollapseRows(1);
secondWorksheet.Rows().Collapse();
pt.EnableShowDetails = false;
pt.ShowValuesRow = false;
secondWorksheet.PageSetup.ShowGridlines = true;
secondWorksheet.ShowGridLines = true;
workbook.PageOptions.ShowGridlines = true;
secondWorksheet.PivotTables.First().EnableShowDetails = false;
This is not currently supported by ClosedXML. Pivot tables are still very much work in progress.
Using ClosedXML.Signed version 0.94.2, this worked for me:
IXLPivotTable pivotTable = workbook.Worksheet("SheetContainingPivotTable").PivotTables.First();
pivotTable.ColumnLabels.ToList().ForEach(x => x.SetCollapsed(true));
pivotTable.RowLabels.ToList().ForEach(x => x.SetCollapsed(true));
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.
I am exporting protected excel sheet using EPPlus in my winform(C#) project. Now I want functionality to allow user to edit ranges in that protected excel sheet using same plugin.
It would be great if you provide Code snippet.
Thanks in advance.
var fileName = "sample.xlsx";
var fileInfo = new FileInfo(fileName);
using (var excel = new ExcelPackage(fileInfo))
{
var ws = excel.Workbook.Worksheets.Add("sheet1");
ws.Protection.IsProtected = true;
ws.ProtectedRanges.Add("editable", new ExcelAddress("C:N"));
excel.Save();
}
I know its very late to reply but may help others. I had a similar issue and was struggling to get sorting and auto-filtering in protected worksheet.
After protecting the worksheet, I have added below two settings that allow sorting and auto-filtering.
ws.Protection.IsProtected = True
ws.Protection.AllowSort = True
ws.Protection.AllowAutoFilter = True
In my case however the next requirement was to unlock some columns to allow editing, I achieved that using:
ws.Column(12).Style.Locked = False
If you have a range however you can try something like this:
For Each cell In ws.Cells("B1:C8")
cell.Style.Locked = False
Next