Adding a Sumif formula to cell error using c# - c#

I'm trying to add a formula to a cell in multiple rows in Excel through C#.
What i'm trying to achieve with the formula is to SUM all the cells which does not contain the string N/A, in column D to S in every row.
This is the formula i'm trying to add:
=SUMIF(DX:SX,"<>N/A")
(In the example above i changed the actual row number with X)
So i'm looping through the rows and doing this:
foreach (var row in rows)
{
ws.Cells[row, 2].Formula = string.Format("=SUMIF(D{0}:S{0},\"<>N/A\")", row + 1);
}
Here I get the exception:
System.ArgumentException : Failed to parse: =SUMIF(D2:S2,"<>N/A"). Error:
Unsupported function: SUMIF.For list of supported functions consult
GemBox.Spreadsheet documentation.
I've also tried to add the Swedish version of the formula which is:
=SUMMA.OM(DX:SX;"<>N/A")
(In the example above i changed the actual row number with X)
and here i get the exception:
System.ArgumentException : Failed to parse: =SUMMA.OM(D2:S2;"<>N/A"). Error:
Not expected: SUMMA
The weirdest part of this is that if i manually enter the swedish formula in the cell in Excel, it works.
Appreciate any help i can get, thank you so much.

I actually don't see any reason it would throw that error -- what you did seems like it should work. In the spirit of offering another avenue to test, you could also try the R1C1 version of the formula and see if that works:
foreach (var row in rows)
{
ws.Cells[row, 2].FormulaR1C1 = "=SUMIF(R[0]C[2]:R[0]C[17],\"<>N/A\")";
}
Unless your rows variable contains an invalid number, I'm not sure why it would throw that exception. In the example error you gave, that should be fine.

Related

C# EPPlus multiple cell formatting not applying

I am using EPPlus to generate excel file from data table. i have only two rows. i am applying % formatting on first row and $ formatting on second row but my two row has getting same % formatting for first two row which is wrong. i am not being able to capture the reason why this is happening. why second formatting not being applied on second row which is $ formatting.
See this line where i use range to apply formatting.
ws.Cells["C0:P0"].Style.Numberformat.Format = "#,###,##0.0%;(#,###,##0.0%)";
ws.Cells["C1:P1"].Style.Numberformat.Format = "$##,##0.0;($##,##0.0)";
in the above code i mention cell range with formatting but my two row getting only first formatting and second formatting not consider...not clear why this is happening?
Sample Code
using (OfficeOpenXml.ExcelPackage obj = new OfficeOpenXml.ExcelPackage(FileLoc))
{
// creating work sheet object
OfficeOpenXml.ExcelWorksheet ws = obj.Workbook.Worksheets.Add("Vertical");
// freezing work sheet columns and rows
ws.View.FreezePanes(2, 3);
// exporting data to excel
ws.Cells["A1"].LoadFromDataTable(selected, true);
// setting calumns as autofit
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//fixing height of column
ws.Row(1).Height = 16;
ws.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Row(1).Style.Fill.BackgroundColor.SetColor(Color.LightGray);
obj.Save();
ws.Cells["C0:P0"].Style.Numberformat.Format = "#,###,##0.0%;(#,###,##0.0%)";
ws.Cells["C1:P1"].Style.Numberformat.Format = "$##,##0.0;($##,##0.0)";
}
screen shot of excel data. see first two line in picture and definitely understand #,###,##0.0%;(#,###,##0.0%) this format is applying on first two row but in my code i have given different format for second records.
please help me to find the wrong things in my code. thanks
Well, there are a couple of errors. First, you're saving before setting the formatting, so it's not being applied.
Second, Excel addresses are base 1, it doesn't exist "C0" and "P0". Also note that in the first row is the columns titles, so you probably want rows 2 and 3. Try the following:
ws.Cells["C2:P2"].Style.Numberformat.Format = "#,###,##0.0%;(#,###,##0.0%)";
ws.Cells["C3:P3"].Style.Numberformat.Format = "$##,##0.0;($##,##0.0)";
obj.Save();

How to get the Excel fields(double) as int

I am trying to read the uploaded Excel content, but the following two methods cannot use reader.GetInt32(1):
I set the Excel field as "common format" and then input a number 1.
--> Show InvalidCastException
I set the Excel field as "integer format" and then input a number 1.
--> Show InvalidCastException
So I confirm the Excel field type, and found out it was a double.
var fieldType = reader.GetFieldType(1);
I have two question:
Is this a setting of Excel itself which causes my get type is a Double?
How to get the Excel fields as int in my case?
Because the content of the fields I should insert into the database must be int.
Try this
try {
int aaa = (int)reader.GetValue(1)
} catch {
//Do something here to log conversion errors
}
Be aware that ADO.NET reads the top rows on the Excel to decide the columns data types. If you have a text at, say, row 200, but the first rows are numeric the column will be numeric and you'll get an error when you read the 200th row.
Also, you can use EPPlus as Excel reader and avoid ADO.NET. In your case, reading an integer value could be
int aaa = sheet.Cells[r, 1].GetValue<int>();
The following can solve my second problem, but I'm still curious about the first question.
Convert.ToInt32(reader.GetValue(1));

Error CS1733: Expected Expression error in writing data in a single row

I'm creating a software using C# that transfers data to an excel file. I want to write different data values in a single range of row.
I've tried to create variables since some parts have the same syntax.
This is my code:
var reflection193 = arLot.ARResultModel.FirstOrDefault(rm => rm.ResultType == ResultType.Reflection193);
Worksheet.Range["C23", "D23"].Value =
("{0} %", "{1} %", (reflection193)?.LowerValue, (reflection193)?.UpperValue);
I expect to have Lower value in cell C23 and Upper value in cell D23 in the excel result. What I'm getting is an "Error cs1733: expected expression". Plus I'm also having an Exception thrown: "'System.ArgumentException' in mscorlib.dll" and
"Exception: Value does not fall within the expected range."

C#: OpenXML numeric Excel cells not returning correct values

this is my first post so sorry if it doesn't look good or if the formatting is weird.
Anyways, I need to find a way to get the correct value of numeric (non-string) cells using OpenXML, but with some spreadsheets my current method doesn't seem to work.
There seems to be a difference in how I need to code for varying spreadsheets.
Once I've accessed an Excel file and have opened one of its Sheets I get the number of columns and rows for the current sheet and begin my loops. Within these loops is the code below that is used to add each cell to the datatable using the Cell Reference (made using the parent loops) as the guide. This is the looped through code:
//making the cell index/location of the cell (for example: B10, E17, AE14, ...) based on our row/column indexing so far
cellRef = ConvertColNumToLetter(startColNum + column) + (y + StartRow).ToString();
//getting the specific cell at the cell index of our cellRef
workingCell = cells.Where(c => c.CellReference == cellRef).FirstOrDefault();
//using a try-catch to solve the issue of the program failing whenever the cell has no inner text to take
try
{
if (workingCell.InnerText == null)
value = "";
else
{
value = workingCell.InnerText;
}
//if the cell's data is a string
if (workingCell.DataType != null && workingCell.DataType.Value == CellValues.SharedString)
{
var stringTable = workbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
if (stringTable != null)
value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
dataRow[colIterator] = value.ToString();
colIterator++;
}
//if the cell's data is numeric
else if (workingCell.CellValue != null)
{
value = workingCell.CellValue.InnerText.ToString();
dataRow[colIterator] = value;
colIterator++;
}
//if the cell doesn't have any data
else
{
dataRow[colIterator] = "";
colIterator++;
}
}
//this will only fail if the cell didn't have any data/the data is null
catch
{
dataRow[colIterator] = "";
colIterator++;
}
My code works just fine for 99% of the spreadsheets it encounters. My only problem is with numeric values not being accessed correctly on one specific spreadsheet but it seems to get the correct numeric values on all other spreadsheets.
With the normal spreadsheets, whatever numeric value that is stored in the formula is returned. As an example, here is a cell's value from one such spreadsheet: "31313308.87". When my program reaches that cell, here is the workingCell's details (the workingCell is the cell at the current cell reference location):
which as you can see are the values that I would want and would go through the program and store the correct values into the datatable.
But the spreadsheet that's giving me issues is strange. When I get to one of the numeric cells I end up just getting the completely wrong values. Opening up the actual spreadsheet, there is a numeric cell with a value of "502028.6", but my program gets this in the workingCell's details:
I'm not sure where the "279907" comes from or how I should go about getting the correct values.
Here's another strange thing. The next three values of the spreadsheet are zeros which all return 0 in the CellValue and InnerText of the workingCell. The next value on the spreadsheet is "-160", and in the workingCell's details it shows:
1500 in the CellValue and InnerText?
Again, this is the only spreadsheet that this is happening on (or at least the only one that I know of). The program returns the correct string values as well, but on this one specific spreadsheet, none of the numeric values seem to be picked up with my program (despite it working and returning the correct numeric values for the hundreds of other spreadsheets I've used it on so far).
Is there some simple fix that I'm just not seeing? I would love any pointers or suggestions you may have for me, and I will be happy to clarify anything if you need some additional information.
Thank you for all of your help in advance!
--EDIT:
I forgot to specify when I asked the question, but the incorrect data (the incorrect CellValues and InnerTexts) is actually successfully processed into the else if statement then added to the datatable. I don't have any problem as far as adding values to the datatable goes, but I just can't seem to get the correct CellValues and InnerTexts for numeric cells on the one specific spreadsheet

EPPlus - Row Out Of Range exception

I'm trying to import datatable with 1000000 records into Excel using EPPlus library.
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
var recordCount = dt.Rows.Count;
ws.Cells["A5"].LoadFromDataTable(dt, true);
I'm getting Row Out of Range exception on ws.Cells["A5"].LoadFromDataTable(dt, true); line
It worked when I had 1000 records.
Is there row limit size when working with EPPlus?
You probably tried to import a little bit more than 1.000.000 records. The maximum before throwing this exception is 1.048.576 (which exactly equals the maximum number of rows specified for Excel version 2010).
Have a look at the source code:
The last line of the LoadFromDataTable method in ExcelRangeBase.cs returns the imported excelrange: _worksheet.Cells[...]
You can find the implementation of this indexer in ExcelRange.cs and there you'll see that the range is validated by ValidateRowCol (all the way at the bottom).
Finally, this validation throws the exception you mentioned when the requested row is larger than the MaxRows property of an excelpackage, which equals 1.048.576
When you get "Row out of range", the row parameter is probably too high or too low.
Remember that it starts to count from 1.
I got this error when I had placed a list in a list. Should have been only a list and not a list in a list.
To be exact i created a list of object that I then placed in a list, parsed to JSON and loaded to a DataTable with JsonConvert.DeserializeObject(json, jsonFormat). Then I got the error.

Categories