I have trouble creating cells in excel using openXml. If I use Datatype Number I get a warning when opening the excel "We found a problem with some content in file.xlsx. Do you want us to try to recover as much as we can?"
And if I use datatype string I get the warning inside excel.
This is the code I use...
Cell newCell = new Cell() { CellReference = cellId };
row.InsertBefore(newCell, refCell);
newCell.CellValue = new CellValue(value);
newCell.DataType = new EnumValue<CellValues>(CellValues.String); // Generate warnings since number is type text in cell
//newCell.DataType = new EnumValue<CellValues>(CellValues.Number); // Generate error when open the file
newCell.StyleIndex = 0;
UPDATE, If I add a decimal value like 10.2 I get this error, but if I add just 10 as value without any decimals there is no error at all. So how can I add decimals without getting this error?
This is probably an issue with localization. The ToString() method of Decimal uses your current locale for the output. In your case that's likely a comma. OpenXML wants dots afaik.
You can force the locale to the ToString() method as shown in the examples here.
e.g.
value.ToString(CultureInfo.CreateSpecificCulture("en-US"));
edit. It could be that you need to do more, and convert it to scientific notation, as described here.
Edit2: Note the existence of OpenXML.DecimalValue
Related
Is there any way to control whether a number displays in scientific notation using the EPPlus library to generate an Excel file in C#?
worksheet.Cells[row, col].Value = someValue; //example value: 0.0000152691
worksheet.Cells[row, col].StyleName = RegularCenterAlign;
worksheet.Cells[row, col].Style.Numberformat.Format = "WHAT DO I PUT HERE???";
I tried "0.00e0" for the format and that causes excel to throw an error:
I didn't see it in the documentation but if you look in Excel at the formatting options, scientific notation is available, so you'd think EPPlus has a string code we could use for this.
What seems to be happening now is Excel is making its own determination about whether to format a given number in scientific notation. The same code inserted all of the numbers in the following screenshot. No format was specified but you can see that last one did not use scientific notation.
Use:
ws.Cells["A1"].Style.Numberformat.Format = "0E+00";
You can add the number of decimals with something like:
ws.Cells["A1"].Style.Numberformat.Format = "0.0000E+00";
Don't forget that your value should be numeric. This value will be formatted:
ws.Cells["A1"].Value = 0.0000152691;
this one won't:
ws.Cells["A1"].Value = "0.0000152691";
I am trying to write to Excel using Excel Interop. One of my column will have a very numeric value (44 digits).
After checking similar posts in the internet, I tried setting the NumberFormat.
worksheet.Cells[i, j].NumberFormat = "#"; and worksheet.Cells[i, j].NumberFormat = "#";
But it still shows the values in format- ######... so on.. I tried expanding the columns too but that did not work. However, this worked for some of my other column where I have numeric values in 14 digits.
Any help? Please let me know if I can provide more details.
There is a 15 digit limit in Excel unfortunately
for cells use cells["A:A"].numberFormat = "#";
for columns use cells[0, 2].EntireColumn.NumberFormat = "#";
If showing the data in text is ok , then set the cell format to TEXT.
I´m trying to apply conditional format to Excel using EPPLUS so that a range of cells is filled with red color if the value is negative.
I try this code that if the value of the cell is bigger that the value of the next cell, that cell is filled with red
ExcelAddress _formatRangeAddress = new ExcelAddress("J2:J"+(listaMargenes.Count+2));
string _statement="IF(OFFSET(J3,0,-1)-J3>0,1,0)";
var _cond4 = hoja.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond4.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond4.Style.Fill.BackgroundColor.Color = System.Drawing.Color.Red;
_cond4.Formula = _statement;
this Works fine, but if i change:
IF(OFFSET(J3,0,-1)-J3>0,1,0)
by this:
if(J3<0)
does not Works, when opening the Excel says there is corrupted data.
any idea of how to write the correct way tu put in red the cells with negative value?
An IF statement in excel does not allow for an optional value_if_true part anymore (I believe in older versions it did): MS IF Documentation
So change it to something like:
string _statement = "if(B3<0, 1)";
I've been googling and searching on the site for the answer, but I couldn't find a solution - everywhere people mostly discuss how to add new number format to the document and apply it.
What I need is to get the cell value as a string with applied formatting - i.e. same string as would be displayed by Excel.
I already figured that there's no easy way or built-in function which would return the readymade formatted value for a cell.
So it seems to me that to get the value I need to do two things:
1. Get the format string.
2. Format the cell value using this string.
But I have problems with both steps.
One can easily get CellFormat instance which would contain NumberFormatId:
CellFormat cellFormat = (CellFormat) document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ElementAt(cell.StyleIndex);
But how to get the format string with this NumberFormatId, if the id corresponds to one of standard predefined formats? (i.e. is below 160) They are not in the spreadsheet document and I can't believe that they should be hardcoded in the application.
Also, once the format string is somehow obtained, how to apply it to the cell value? So far I understand, the code should check the type of the cell value and if is Number - convert it to string using the format string.
I found this page which mentions using Microsoft.Office.Excel.Interop, but I would prefer to stay with OpenXML SDK only.
Overall, I'm very surprised that it's so difficult to find a definitive answer to this question on the Web as I thought that this would be something which many developers need in their daily work.
Men, this is a hard one... I will be adding here things that i found that could be worth..
First is to get the numbering format of the cell (once you have the CellFormat:
string format = excel.WorkbookPart.WorkbookStylesPart.Stylesheet.NumberingFormats.Elements<NumberingFormat>()
.Where(i => i.NumberFormatId.ToString() == cellFormat.NumberFormatId.ToString())
.First().FormatCode;
For more information about this you can go to: NumberingFormats
Im trying to find out how to apply this format to the cell.CellValue property... I think thats the way you have to go!
Ok, reading the ClosedXml code (its open source), seems to be easy to get the format.
Simply convert the value text to its type (int, double, etc) and call the ToString method passing the format. I was trying do that with the String.Format and didnt work. Ive tested the ToString and it works, but something still missing.
I recommend to you to look at this class and get the code from the method GetFormattedString() as #El G tell in his comment.
Bassicaly you will have to add something like this:
double d = double.Parse(cell.CellValue.InnerText);
string val = d.ToString(format);
Hope it helps you...
If you want to take cell value with applied formatting, same as displayed in Excel, use .Text property of Cell object. Like this:
String formattedValue = cell.Text
I'm attempting to format a cell in excel to the currency format. So I go into excel, record a macro of me converting an ordinary cell to a currency format, take a look at the vb script and see that it outputs the following:
NumberFormat = "$ #,##0.00"
So i take that format and paste it into my code, it works to the extent that im getting the currency character before the values in my excel sheet. However, the format of the cell is still a number and excel places a little green triangle at the bottom left of the cell informing me that the format is incorrect (which it is, cos its supposed to be currency, but its set to number) is there any way in c# to actually set the cell to a "Currency" format?
thanks
The range object has a "Style" property... the intelisense metadata says that it is "Returns an object you can use" only but you can also just set the Style with that property. To get the built-in "Currency" style, use the "Styles" property of (for instance) a Workbook object.
Example:
using Excel = Microsoft.Office.Interop.Excel;
...
var excel = new Excel.Application();
var wb = excel.Workbooks.Add();
var sheet = (Excel.Worksheet)wb.Sheets[1];
((Excel.Range)sheet.Cells[3, 4]).Style = wb.Styles["Currency"];
In fact you can just set it to the string "Currency" which may be what Charles was suggesting.
((Excel.Range)sheet.Cells[3, 4]).Style = "Currency";
Ok i tried many that codes and i found this works better than other on any language/regional settings.
numberFormat = #"_-[$$-409]* #,##0.00_ ;_-[$$-409]* -#,##0.00 ;_-[$$-409]* ""-""??_ ;_-#_ ";
Not sure I understand your question:In Excel all numeric values including currency, integers and date/time are held as floating-point doubles. The Format of a value only controls how it is presented in the rendering (visible) layer. The green triangle tests do not include tests for formatting. Is the problem that you are creating a text value rather than a numeric value?