EPPlus cells not updated after number format - c#

Im trying to change number format with epplus in excel to this format ([h]:mm:ss), and it seems to change the cells format correctly. But the cells value doesnt update after the format...
As the picture shows the correct way of the text should be like the first cell on the picture. It works if I click on the cells and presses enter againPicture
var sheet = package.Workbook.Worksheets.Add(filename);
var tableRange = sheet.Cells["A1"].LoadFromCollection(list);
var table = sheet.Tables.GetFromRange(tableRange);
package.Save();
NumberFormat
[EpplusTableColumn(Order = 2, NumberFormat = "[h]:mm:ss")]
public string timeWorked { get; set; }
In the end, I want to use the SUM function in excel to calculate the total timeworked, but it doesnt work when the cells doesnt change to the format I have sat for it

Firstly, change type from string to TimeSpan
public TimeSpan TimeWorked { get; set; } = new TimeSpan(2, 18, 19);
Secondly, set printHeader to true
var tableRange = sheet.Cells["A1"].LoadFromCollection(actors, true);
For some reason column when using EpplusTableColumn attribute headers need to be included in excel otherwise cell formatting doesn't work. I'm not sure if it's a bug or am I missing something.
Would love if someone can give me more explanation.
If you really don't want headers to show there is a workaround. Before saving remove first row from excel.
sheet.DeleteRow(1);
package.Save();

Related

NPOI doesn't apply format to .xls

C#, NPOI
Good evening, i'm trying to fill in an empty template with values(numbers, but in string variable), that needs to be in cells.
So, when it came to formatting, i've stuck with styling. That means, when i wrote the value inside(in pre-formatted cell) i get just the string value, that was in array.
But, when i open file, click "edit cell", then apply without any changes, then cell is formatted, with the format, which was in a template
I tried to apply previous style in cell(basically just copy style in var, before setting a value, then re-apply style), but, it didnt help.
Here is the video of my doings
var cr = new CellReference(cellAndValue[i, 0]);
var row = sheet?.GetRow(cr.Row);
var cell = row?.GetCell(cr.Col);
var prevtype = cell.CellType;
var prevstyle = cell.CellStyle;
var dataformat = cell.CellStyle.DataFormat;
CellType type = cell.CellType;
cell.SetCellValue(cellAndValue[i, 0]);
How to resolve that?)
It was required to convert incoming data to int, before inserting it XD
int n;
if (Int32.TryParse(cellAndValue[i, 1], out n))
{
cell.SetCellValue(n);
}
else
{
cell.SetCellValue(cellAndValue[i, 1]);
}

Date column is not set properly in open XML Excel

I am trying to copy the data in excel sheet but it does not show properly it is show like ####### but I want 17-09-2016 like this.kindly suggest me what code I am write to export the excel in proper format.
Code:
var rngTable2 = ws.Range("A:G");
var rngHeaders2 = rngTable2.Range("F4:G4");
rngHeaders2.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.General;
rngHeaders2.Style.Alignment.Vertical = XLAlignmentVerticalValues.Bottom;
Date comes from this code:
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString("dd/MM/yyyy")).Value = myVal1;
index5++;
Ultimately, it seems like you're trying to get a date from a label and then put this value into a load of cells within column F somewhere. I'm guessing you have this within a for loop as well seeing as you're incrementing index5. So something like this should work:
//Make column F a date column. Alter to a specific range if the whole column shouldn't be of date type.
Range rg = ws.Range("F:F");
rg.EntireColumn.NumberFormat = "DD/MM/YYYY";
var lblpkgdate = (Label).gvvessel.Rows[j].FindControl("lblpackagedate");
//Convert lblpkgdate text to DateTime object assuming format of dd/MM/yyyy to ensure it is actually a date.
DateTime pkgDate = DateTime.ParseExact(lblpkgdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for(int i = 1, i < YourMaxRowValue, i++)
{
ws.Cell("F" + i).Value = pkgDate;
}
NOTE - I've altered index5 to 'i' as this is less misleading if you're looping. I've also altered myVal1 to pkgDate as I think this is more meaningful.
you can use NumberFormat
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString()).Style.NumberFormat.Format = "DD-MM-YYYY";
ws.Cell("F" + index5.ToString()).Value = myVal1;
index5++;

Keep excel cell format as text with "date like" data

This seems silly, but I haven't been able to get my values in the format of #/#### to write as the literal string rather than becoming formatted as a date within excel.
I'm using ClosedXML to write to excel, and using the following:
// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).DataType = XLCellValues.Text;
tableRow.Cell(1).Value = "2/1997";
// snip
Looking at the output excel sheet I get in the cell 2/1/1997 - even though I'm setting the format as text in code, I'm getting it as a "Date" in the excel sheet - I checked this by right clicking the cell, format cell, seeing "date" as the format.
If I change things up to:
// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).Value = "2/1997";
tableRow.Cell(1).DataType = XLCellValues.Text;
// snip
I instead get 35462 as my output.
I just want my literal value of 2/1997 to be displayed on the worksheet. Please advise on how to correct.
try this
ws.Cell(rowCounter, colCounter).SetValue<string>(Convert.ToString(fieldValue));
Not sure about from ClosedXML, but maybe try Range.NumberFormat (MSDN Link)
For example...
Range("A1").NumberFormat = "#"
Or
Selection.NumberFormat = "#/####"
Consider:
tableRow.Cell(1).Value = "'2/1997";
Note the single quote.
ws.Cell(rowCounter, colCounter).Value="'"+Convert.ToString(fieldValue));
Formatting has to be done before you write values to the cells.
I had following mechanism, run after I make worksheet, right before I save it:
private void SetColumnFormatToText(IXLWorksheet worksheet)
{
var wholeSheet = worksheet.Range(FirstDataRowIndexInExcel, StartCellIndex, RowCount, HeaderCount);
wholeSheet.Style.NumberFormat.Format = "#";
}
which didn't do squat.
Doing it before I write values to the cells in a row did it.
worksheet.Range(RowIndex, StartCellIndex, RowIndex, EndCellIndex).Style.NumberFormat.Format = "#";
with cell value assignments following immediately after.

Changing DataType of cell to Double

I'm using OpenXML to create Microsoft Excel file. I'm trying to insert a double type variable (Example : 4.987456789) into the Excel using
Cell cell = new Cell()
{
CellReference = "A2",
DataType = CellValues.String,
CellValue = new CellValue(Convert.ToString(value))
};
But, when the cell is being made, it's in text form and Excel says "The number in this cell is formatted as text or preceded by an apostrophe." How can format the cell to insert double?
Edit :
Sorry, It's double? type and I follow this tutorial
Using CellValues.Number works fine for me, for example :
double? value = 4.9874567891;
Cell cell2 = new Cell()
{
CellReference = "A2",
DataType = CellValues.Number,
CellValue = new CellValue(Convert.ToString(value))
};
Double value printed to excel without the warning you got.
I had the same problem. I followed the advices from the various posts and answers applying a style on the cell... no success.
Finally I found the origin of the problem and so the solution :
In my loop, I inserted all data in the same way i.e. using the InsertSharedStringItem() function.
If you insert a number in your spreadsheet like that, the cell formating will be useless and your number will not be considered as a number.
What you should do is to insert it "directly".
index =InsertSharedStringItem(myStringNumber, shareStringPart);
cell = InsertCellInWorksheet("A", 1, worksheetPart);
cell.CellValue = new CellValue(index.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = _doubleStyleId;
will not work.
cell = InsertCellInWorksheet("A", 1, worksheetPart);
cell.CellValue = new CellValue(myStringNumber);
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.StyleIndex = _doubleStyleId;
is OK
with as Claies wrote :
Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet;
_doubleStyleId = createCellFormat(styleSheet, null,null, UInt32Value.FromUInt32(4));
the code for createCellFormat() can be found here
OpenXML always creates a cell as Inline Text, and relies upon formatting to determine the correct display format within Excel. Each number format in Excel corresponds to a unique code, and a style can be applied to the cell, the same way you might change the style from within Excel.
The OpenXML Standard defines a series of codes which can be assigned without creating a custom StyleSheet.
The implied format for a double is 4 #,##0.00
so first you create the styleId:
Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet;
_doubleStyleId = createCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4));
then, set the styleId on the cell:
cell.StyleIndex = _doubleStyleId;
Super late to this party but I ran into this problem and to me the solution was in the default stringifying of my local language, presumably the use of ',' as a decimal delimiter
Cell cell = new Cell() {
DataType = CellValues.Number,
CellValue = new CellValue(value.ToString(new CultureInfo("en-US"))) };
solved it for me.

NPOI Excel number format not showing in Excel sheet in asp.net

I am trying to create double and number format cells in excel using NPOI library. I used code like
Dim cell As HSSFCell = row.CreateCell(j)
cell.SetCellValue(Double.Parse(dr(col).ToString))
In excel numbers are aligning right but when I check format it is showing in "General"
then I changed my code to like below
Dim cell As HSSFCell = row.CreateCell(j)
cell.SetCellValue(Double.Parse(dr(col).ToString))
Dim cellStyle As HSSFCellStyle = hssfworkbook.CreateCellStyle
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,#0.0")
cell.CellStyle = cellStyle
Then While opening file it is giving error and also taking so long to open. But Excel format showing in "Number"
error showing is like below.
How to fix this?
Take a look at this, are you creating a cellStyle object for each cell? If so don't. Try creating just a couple of styles before creating your cells and then apply these pre-defined styles to the cells you create.
To fix the too many different cell styles declare all styles outside of any loop you may be running.
I'm presumeing you 'j' would be the enumerator so i'll drop what you had in a corrected format for you.
Dim cellStyle As HSSFCellStyle = hssfworkbook.CreateCellStyle
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,#0.0")
For col = 0 To ColoumCounter
For j = 0 To Counter
Dim cell As HSSFCell = row.CreateCell(j)
cell.SetCellValue(Double.Parse(dr(col).ToString))
cell.CellStyle = cellStyle
Next
Next
This should work a bit better, by limiting the number of "New" styles.
Hare is a simple way to create double format in Excel Document USING NPOI.
//make NUMERIC Format in Excel Document // Author: Akavrelishvili
var eRow = sheet.CreateRow(rowIndex); //create new Row , rowIndex - it's integer, like : 1,2,3
eRow.CreateCell(0).SetCellValue(row["ProvidName"].ToString()); //create cell and set string value
double Amount = Convert.ToDouble(row["Amount"].ToString()); //convert string to double
eRow.CreateCell(1).SetCellValue(Amount); // create cell and set double value.
This is working version, I have used it a lots of projects.
Very Hard is to insert DateTime format in Excel, There no good example in Internet and I think it helps people to do it right way.
I show you code example:
//make Date Time Format in Excel Document // Author: Akavrelishvili
var eRow = sheet.CreateRow(rowIndex); //create new Row // rowIndex - it's integer, like : 1,2,3
ICellStyle cellDateStyle = workBook.CreateCellStyle(); //create custom style
cellDateStyle.DataFormat = workBook.CreateDataFormat().GetFormat("dd/mm/yyyy"); //set day time Format
eRow.CreateCell(3).SetCellValue(Convert.ToDateTime(row["Date"])); //set DateTime value to cell
eRow.GetCell(6).CellStyle = cellDateStyle; // Restyle cell using "cellDateStyle"
I hope it helps
Create a style then but this style for the column
ICellStyle _TextCellStyle = wb1.CreateCellStyle();
_TextCellStyle.DataFormat = wb1.CreateDataFormat().GetFormat("#");
sheet.SetDefaultColumnStyle(2, _TextCellStyle);

Categories