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)";
Related
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
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 am trying to use Microsoft.Office.Interop.Excel to read excel file in c#.
I want to read range of cells as it is way faster than reading cell one by one:
Range rbeg = (Range)sheet.Cells[1, i + 1];
Range rend = (Range)sheet.Cells[totalRowCount, i + 1];
Range range = sheet.get_Range(rbeg, rend);
column = (object[,])range.Value2;
The problem is when I want to get number format of cells by calling:
range.NumberFormat
I get System.DBNull. It works when I call it for single cell.
I want to distinguish between cells with numerical values and "%" values.
Any ideas?
See the documentation:
[NumberFormat] returns Null if all cells in the specified range
don't have the same number format.
What were you expecting it to do in this case?
I'm using NPOI to output excel from Asp.Net MVC app and works very well with plain text but have now been requested to add formatting and am having problems where I need to have a single cell with bold text followed by non-bold text. e.g.
This text bold - this text normal
I know I can give a cell a single style but this won't help and I cannot see anyway to give a cell some pre-formatted rich text.
The only possible solution that I can think of is creating two cells separately and the merge them together but will that then mean the formatting will be lost?
Is there a way to do this that I have missed in NPOI?
You may try this:
var font = reportWorkbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
var cell = headerRow.CreateCell(0);
cell.SetCellValue("Test Bold");
cell.CellStyle = reportWorkbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
Fortunately, you able to do that... Look at this code:
Font f1=wb.CreateFont();
f1.Color=HSSFColor.RED.index;
ws.GetRow(1).GetCell(0).RichStringCellValue.ApplyFont(1, 5, f1);
Seems that the Ernie Banzon answer no longer works exactly as described, possibly due to a namespace change (or in fact that I'm using the HSSF namespace?)
// usings
using NPOI.HSSF.UserModel;
// IWorkbook doc
IFont font = doc.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Arial";
font.Boldweight = (short)FontBoldWeight.BOLD;
Use this option
font.Boldweight = (short)700;//FontBoldWeight.Bold;
Actual syntax should be like below. But both of these syntax doesn't works sometime
font.Boldweight = FontBoldWeight.Bold ;
Or
font.Boldweight = (short)FontBoldWeight.Bold;
FontBoldWeight is type enum, which after type casting may not work sometime. As a workaround if you type caste or use actual short value of enum directly, it works. Below is the declaration of FontBoldWeight. it will make things clear.
**public enum FontBoldWeight
{
None = 0,
Normal = 400,
Bold = 700,
}**
After a fair amount of investigation it seems that you are not able to do this inside of NPOI as it doesn't provide the necessary functionality to allow you to set formatting on specific text within a cell like I was attempting to do.
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?