How to add Excel cell background color file by X++ in Dynamics 365? - axapta

I'm creating an Excel file by x++, in Dynamics 365 - D365, I would like to add the background color by X++.
I'm using this code
System.IO.Stream workbookStream = new System.IO.MemoryStream();
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
var package = new OfficeOpenXml.ExcelPackage(memoryStream)
var package = new OfficeOpenXml.ExcelPackage(memoryStream)
var worksheets = package.get_Workbook().get_Worksheets();
var worksheet = worksheets.Add("SHEET");
var cells = worksheet.get_Cells();
var currentRow=1 ;
var cell = cells.get_Item(currentRow,1);
cell.set_Value("__MY__Value");
// NOT Work - compile error
//cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color::FromArgb(190, 0, 0));
//cell.Style.Fill.BackgroundColor.Rgb(Winapi::rgb2int(255,255,255));
Both commented lines give a Invalid token '('. compiler error.
How can I use the Background color property about Excel cell, by X++ in right way?
Thanks in advance.

As is often the case when doing .Net Interop from x++, the compiler can be a bit difficult if you mix a chain of properties and method calls. It usually helps to put the last property of the chain into its own variable and then call the method on that variable.
So instead of writing
cell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color::FromArgb(190, 0, 0));
write this instead:
ExcelColor backgroundColor = cell.Style.Fill.BackgroundColor;
backgroundColor.SetColor(System.Drawing.Color::FromArgb(190, 0, 0));
This will get rid of the Invalid token '('. error.
However, now a runtime exception System.ArgumentException: Can't set color when patterntype is not set. is thrown. This is because OpenOfficeXml expects a fill style along with a background color so that Excel knows how the background color should be applied to the background. See the GettingStartedSample.cs#L57-L64.
I wrote the following code as a runnable class example that produces an Excel file with two values with background colors.
using OfficeOpenXml;
using OfficeOpenXml.Style; // note the additional namespace
class SOCreateExcelWithBackgroundColor
{
public static void main(Args _args)
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add('CellBackground');
// add some values and colors
ExcelRange cell = worksheet.Cells.get_Item('A1');
cell.Value = 'Value1';
ExcelFill fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle::Solid;
ExcelColor backgroundColor = fill.BackgroundColor;
backgroundColor.SetColor(System.Drawing.Color::FromArgb(0, 87, 183));
cell = worksheet.Cells.get_Item('A2');
cell.Value = 'Value2';
fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle::Solid;
backgroundColor = fill.BackgroundColor;
backgroundColor.SetColor(255, 255, 215, 0); // note that the first 255 defines the transparency (alpha value) of the color
package.Save();
}
File::SendFileToUser(stream, 'CellBackground.xlsx');
}
}
}
This creates the following Excel:

Related

How to add fontawasome icon as a layer in geotools using javafx (Desktop App)?

I have been using java 17 and I'm unable to add icons into the map as a layer. please help me.
void drawTarget(double x, double y) {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("MyFeatureType");
builder.setCRS( DefaultGeographicCRS.WGS84 ); // set crs
builder.add("location", LineString.class); // add geometry
// build the type
SimpleFeatureType TYPE = builder.buildFeatureType();
// create features using the type defined
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
// GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
// Coordinate[] coords =
// new Coordinate[] {new Coordinate(79,25.00), new Coordinate(x, y)};
// line = geometryFactory.createLineString(coords);
// ln = new javafx.scene.shape.Line();
FontAwesomeIcon faico = new FontAwesomeIcon();
faico.setIconName("FIGHTER_JET");
faico.setX(76);
faico.setY(25);
faico.setVisible(true);
// TranslateTransition trans = new TranslateTransition();
// trans.setNode(faico);
featureBuilder.add(faico);
SimpleFeature feature = featureBuilder.buildFeature("FeaturePoint");
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("external", TYPE);
featureCollection.add(feature); // Add feature 1, 2, 3, etc
Style style5 = SLD.createLineStyle(Color.YELLOW, 2f);
Layer layer5 = new FeatureLayer(featureCollection, style5);
map.addLayer(layer5);
// mapFrame.getMapPane().repaint();
}
I want to add a font-awesome icon to the map
Currently, your code is attempting to use an Icon as a Geometry in your feature. I'm guessing that's what isn't working since you don't say.
If you want to use an Icon to display the location of a Feature then you will need two things.
A valid geometry in your feature, probably a point (since an Icon is normally a point)
A valid Style to be used by the Renderer to draw your feature(s) on the map. Currently, you are asking for the line in your feature to be drawn using a yellow line (style5 = SLD.createLineStyle(Color.YELLOW, 2f);)
I can't really help with step 1, since I don't know where your fighter jet currently is.
For step 2 I suggest you look at the SLD resources to give you some clues of how the styling system works before going on the manual to see how GeoTools implements that.
Since you are trying to add an Icon I suggest you'd need something like:
List<GraphicalSymbol> symbols = new ArrayList<>();
symbols.add(sf.externalGraphic(svg, "svg", null)); // svg preferred
symbols.add(sf.externalGraphic(png, "png", null)); // png preferred
symbols.add(sf.mark(ff.literal("circle"), fill, stroke)); // simple circle backup plan
Expression opacity = null; // use default
Expression size = ff.literal(10);
Expression rotation = null; // use default
AnchorPoint anchor = null; // use default
Displacement displacement = null; // use default
// define a point symbolizer of a small circle
Graphic city = sf.graphic(symbols, opacity, size, rotation, anchor, displacement);
PointSymbolizer pointSymbolizer =
sf.pointSymbolizer("point", ff.property("the_geom"), null, null, city);
rule1.symbolizers().add(pointSymbolizer);
featureTypeStyle.rules().add(rule1);
But that assumes that you can convert your FontAwesomeIcon into a static representation that the renderer can draw (png, svg). If it doesn't work like that (I don't use JavaFX) then you may need to add a new MarkFactory to handle them.

With Aspose Cells, how to copy a Cell formula to another cell and update its references in .Net Core without its formating

I'm using Aspose Cells with .net Core.
I would like to copy a cell formula to another cell and update the cells references in the formula with its new "location".
If I use the cell.copy it's working but It's copy also the cell attributes, like 'locked'.
Is there way around it?
Like when using MS-Excel and you do a “Special Paste Formula Only”
I post my question on the Aspose Forum and got a quick answer from #Amjad Sahi
https://forum.aspose.com/t/copy-formula-from-a-cell-to-another-with-updated-references-without-the-source-cell-attribute-like-locked/239996/2
It's worked for me.
I end up with this:
public void CopyFormulaFrom(ICell cell)
{
var cells = cell.Sheet.Name == Sheet.Name
? _cell.Worksheet.Cells
: _cell.Worksheet.Workbook.Worksheets[cell.Sheet.Name]?.Cells;
var cellSource = cells.CreateRange(cell.Row, cell.Column, 1, 1);
var cellDestination = cells.CreateRange(_cell.Row, _cell.Column, 1, 1);
var options = new PasteOptions() { PasteType = PasteType.Formulas };
cellDestination.Copy(cellSource, options);
}

We found a problem with some content in "example.xlsx" - using ClosedXML library

I'm using ClosedXML library to generate a simple Excel file with 2 worksheets.
I keep getting error message whenever i try to open the file saying
"We found a problem with some content in "example.xlsx". Do you want us to try to recover as much as we can. if you trust source of this workbook, click Yes"
If i click Yes, it displays the data as expected, i don't see any
problems with it. Also if i generate only 1 worksheet this error does
not appear.
This is what my stored procedure returns, first result set is populated in sheet1 and second result set is populated in sheet2, which works as expected.
Workbook data
Here is the method i am using, it returns 2 result sets and populates both result sets in 2 different worksheets:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult POAReport(POAReportVM model)
{
POAReportVM poaReportVM = reportService.GetPOAReport(model);
using (var workbook = new XLWorkbook())
{
IXLWorksheet worksheet1 = workbook.Worksheets.Add("ProductOrderAccuracy");
worksheet1.Cell("A1").Value = "DATE";
worksheet1.Cell("B1").Value = "ORDER";
worksheet1.Cell("C1").Value = "";
var countsheet1 = 2;
for (int i = 0; i < poaReportVM.productOrderAccuracyList.Count; i++)
{
worksheet1.Cell(countsheet1, 1).Value = poaReportVM.productOrderAccuracyList[i].CompletedDate.ToString();
worksheet1.Cell(countsheet1, 2).Value = poaReportVM.productOrderAccuracyList[i].WebOrderID.ToString();
worksheet1.Cell(countsheet1, 3).Value = poaReportVM.productOrderAccuracyList[i].CompletedIndicator;
countsheet1++;
}
IXLWorksheet worksheet2 = workbook.Worksheets.Add("Summary");
worksheet2.Cell("A1").Value = "Total Orders Sampled";
worksheet2.Cell("B1").Value = "Passed";
worksheet2.Cell("C1").Value = "% Passed";
worksheet2.Cell(2, 1).Value = poaReportVM.summaryVM.TotalOrdersSampled.ToString();
worksheet2.Cell(2, 2).Value = poaReportVM.summaryVM.Passed.ToString();
worksheet2.Cell(2, 3).Value = poaReportVM.summaryVM.PassedPercentage.ToString();
//save file to memory stream and return it as byte array
using (var ms = new MemoryStream())
{
workbook.SaveAs(ms);
ms.Position = 0;
var content = ms.ToArray();
return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
}
I had similar problem. For me the cause was as mentioned in this answer:
I had this issue when I was using EPPlus to customise an existing template. For me the issue was in the template itself as it contained invalid references to lookup tables. I found this in Formula -> Name Manager.
You may find other solutions there.
Apologies as my reputation is too low to add a comment.

Can PDFsharp automatically split a string over multiple pages?

I want to add the ability to generate a PDF of the content in my application (for simplicity, it will be text-only).
Is there any way to automatically work out how much content will fit in a single page, or to get any content that spills over one page to create a second (third, fourth, etc) page?
I can easily work it out for blocks of text - just split the text by a number of characters into a string array and then print each page in turn - but when the text has a lot of white space and character returns, this doesn't work.
Any advice?
Current code:
public void Generate(string title, string content, string filename)
{
PdfDocument document = new PdfDocument();
PdfPage page;
document.Info.Title = title;
XFont font = new XFont("Verdana", 10, XFontStyle.Regular);
List<String> splitText = new List<string>();
string textCopy = content;
int ptr = 0;
int maxCharacters = 3000;
while (textCopy.Length > 0)
{
//find a space in the text near the max character limit
int textLength = 0;
if (textCopy.Length > maxCharacters)
{
textLength = maxCharacters;
int spacePtr = textCopy.IndexOf(' ', textLength);
string startString = textCopy.Substring(ptr, spacePtr);
splitText.Add(startString);
int length = textCopy.Length - startString.Length;
textCopy = textCopy.Substring(spacePtr, length);
}
else
{
splitText.Add(textCopy);
textCopy = String.Empty;
}
}
foreach (string str in splitText)
{
page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 600);
gfx.DrawRectangle(XBrushes.Transparent, rect);
tf.DrawString(str, font, XBrushes.Black, rect, XStringFormats.TopLeft);
}
document.Save(filename);
}
You can download PDFsharp together with MigraDoc. MigraDoc will automatically add pages as needed, you just create a document and add your text as paragraphs.
See MigraDoc samples page:
http://pdfsharp.net/wiki/MigraDocSamples.ashx
MigraDoc is the recommended way.
If you want to stick to PDFsharp, you can use the XTextFormatter class (source included with PDFsharp) to create a new class that also supports page breaks (e.g. by returning the count of chars that fit on the current page and have the calling code create a new page and call the formatter again with the remaining text).

How to use superscripting in flex?

I want to add a label in flex to display m/s2 (read meters per second square). I would need to use superscripting for this.
I have tried out the following code which is giving me a compilation error.
var richtxt1:RichText = new RichText();
richtxt1.text="m/s";
var richtxt2:RichText = new RichText();
var span:SpanElement = new SpanElement();
span.text = "2";
span.baselineShift = "superscript";
richtxt2.addChild(span);
richtxt1.text=rixhtxt1.txt + richtxt2.text
I am getting a compilation error for the line richtxt2.addChild(span)
The error is
Implicit coercion of a value of type flashX.textLayout.elements.SpanElement
to unrelated type flash.Display.DisplayObject
I think you've to do something like this
var xmlText:String = "<TextFlow xmlns='http://ns.adobe.com/textLayout/2008'>" +
"m/s <span baselineShift='superscript'>2</span>" +
"</TextFlow>";
var txtFlow:TextFlow = TextFlowUtil.importFromXML(xmlText);
var richTxt:RichText = new RichText();
richtxt.textFlow = txtFlow;
I've not tested it so please excuse me of any compilation errors.
This is the code I used in my iPad app to accomplish the above:
var xmlText:String = "m/s <span baselineShift='superscript'>2</span>";
var txtFlow:TextFlow = TextFlowUtil.importFromString(xmlText);
var richTxt:RichText = new RichText();
richTxt.textFlow = txtFlow;
this.addElement(richTxt);
It is based on kaychaks and information I found from Adobe's website. The differences are
I took out the TextFlow markup but left in the HTML;
importFromString rather than importFromXML; and
I added this.addElement(richText) to display the element.

Resources