Excel Date column returning INT using EPPlus - c#

So i'm using EPPlus to read and write excel documents.
Workflow
User generates populated excel document
Opens document and adds a row
Uploaded and read
The dates that are generated when I create the document using EPPlus show correctly when I'm reading the value back but the row the user changes the date one or adds is showing as an INT value not something I can use as a real date.
When I enter the date 1/01/2014 and write it, the output when I open the file up shows 41640
I'm reading it as follows
sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value != null
? sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value.ToString().Trim()
: string.Empty
Update
When exporting the file I have added the following
DateTime testDate;
if (DateTime.TryParse(split[i], out testDate))
{
sheet.Cells[row, i + 1].Style.Numberformat.Format = "MM/dd/yyyy";
sheet.Cells[row, i + 1].Value = testDate.ToString("MM/dd/yyyy");
}
Also when reading the value back I have tried
sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Style.Numberformat.Format = "MM/dd/yyy";
I still get an INT back

...when I need to read that excel file, the only dates that are
incorrect are the ones the user has changed
So when you read the modified excel-sheet, the modified dates are numbers whereas the unchanged values are strings in your date-format?
You could get the DateTime via DateTime.FromOADate:
long dateNum = long.Parse(worksheet.Cells[row, column].Value.ToString());
DateTime result = DateTime.FromOADate(dateNum);
With your sample-number:
Console.Write(DateTime.FromOADate(41640)); // -> 01/01/2014

I stumbled upon this issue today when trying to generate some Excel documents from some ASP.NET DataTables: I had no problem with strings, but ran into few issues with numeric types (int, doubles, decimals) and DataTables, which were formatted as string or as numeric representations (OADate).
Here's the solution I eventually managed to pull off:
if (dc.DataType == typeof(DateTime))
{
if (!r.IsNull(dc))
{
ws.SetValue(row, col, (DateTime)r[dc]);
// Change the following line if you need a different DateTime format
var dtFormat = "dd/MM/yyyy";
ws.Cells[row, col].Style.Numberformat.Format = dtFormat;
}
else ws.SetValue(row, col, null);
}
Apparently, the trick was to set the value as DateTime and then configure the proper Style.Numberformat.Formataccordingly.
I published the full code sample (DataTable to Excel file with EPPlus) in this post on my blog.

You should try using
string dateFromExcel = workSheet.Cells[row, col].Text.ToString();
DateTime localdt;
if (DateTime.TryParse(dateFromExcel, out localdt))
{
dateFromExcel = localdt.ToString("MM/dd/yyyy");
};
the Value reads the value in the general formatting while Text reads the value as it is from the excel with applied formatting.

you could check if the cell format is in date format,
then parse it to date
var cell = worksheet.Cells[row, col];
value = cell.Value.ToString();
if (cell.Style.Numberformat.Format == "[$-409]d\\-mmm\\-yy;#")
{
string inputString = DateTime.FromOADate(long.Parse(value.ToString())).ToString("dd-MMM-yyyy");
}

You can also change the 'NumberFormatLocal' property. This worked for me. If you format the Excel file before improting it using EPPLUS.
The following basic example of code formats column A in a typical excel file.
Sub ChangeExcelColumnFormat()
Dim ExcelApp As Excel.Application
Dim ExcelWB As Excel.Workbook
Dim ExcelWS As Excel.Worksheet
Dim formatRange As Excel.Range
Dim strFile As String = "C:\Test.xlsx"
Dim strSheetname As String = "Sheet1"
ExcelApp = New Excel.Application
ExcelWB = ExcelApp.Workbooks.Open(strFile)
strColSelect = "A:A"
strFormat = "dd/mm/yyyy"
formatRange = ExcelWS.Range(strColSelect)
formatRange.NumberFormatLocal = strFormat
ExcelWB.Save()
ExcelWB.Close()
ExcelApp.Quit()
ExcelWS = Nothing
ExcelWB = Nothing
ExcelApp = Nothing
End Sub

Related

My Program does not insert '00' to my excel [duplicate]

I am losing the leading zeros when I copy values from a datatable to an Excel sheet. That's because probably Excel treats the values as a number instead of text.
I am copying the values like so:
myWorksheet.Cells[i + 2, j] = dtCustomers.Rows[i][j - 1].ToString();
How do I format a whole column or each cell as Text?
A related question, how to cast myWorksheet.Cells[i + 2, j] to show a style property in Intellisense?
Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:
IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "#";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "#";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(#"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);
Disclaimer: I own SpreadsheetGear LLC
If you set the cell formatting to Text prior to adding a numeric value with a leading zero, the leading zero is retained without having to skew results by adding an apostrophe. If you try and manually add a leading zero value to a default sheet in Excel and then convert it to text, the leading zero is removed. If you convert the cell to Text first, then add your value, it is fine. Same principle applies when doing it programatically.
// Pull in all the cells of the worksheet
Range cells = xlWorkBook.Worksheets[1].Cells;
// set each cell's format to Text
cells.NumberFormat = "#";
// reset horizontal alignment to the right
cells.HorizontalAlignment = XlHAlign.xlHAlignRight;
// now add values to the worksheet
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
}
}
Solution that worked for me for Excel Interop:
myWorksheet.Columns[j].NumberFormat = "#"; // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "#"; // cell as a text
This code should run before putting data to Excel. Column and row numbers are 1-based.
A bit more details. Whereas accepted response with reference for SpreadsheetGear looks almost correct, I had two concerns about it:
I am not using SpreadsheetGear. I was interested in regular Excel
communication thru Excel interop without any 3rdparty libraries,
I was searching for the way to format column by number, not using
ranges like "A:A".
Before your write to Excel need to change the format:
xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
Dim cells As Excel.Range = xlWorkSheet.Cells
'set each cell's format to Text
cells.NumberFormat = "#"
'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
Setting the numberFormatting to # causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
Use your WorkSheet.Columns.NumberFormat, and set it to string "#", here is the sample:
Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "#";
Note: this text format will apply for your hole excel sheet!
If you want a particular column to apply the text format, for example, the first column, you can do this:
workSheet.Columns[0].NumberFormat = "#";
or this will apply the specified range of woorkSheet to text format:
workSheet.get_Range("A1", "D1").NumberFormat = "#";
if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
{
myWorksheet.Cells[i + 2, j].NumberFormat = "#";
}
I know this question is aged, still, I would like to contribute.
Applying Range.NumberFormat = "#" just partially solve the problem:
Yes, if you place the focus on a cell of the range, you will read text in the format menu
Yes, it align the data to the left
But if you use the type formula to check the type of the value in the cell, it will return 1 meaning number
Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text
//where [1] - column number which you want to make text
ExcelWorksheet.Columns[1].NumberFormat = "#";
//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.
//path were excel file is kept
string ResultsFilePath = #"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
ExcelApp.Visible = true;
//Looping through all available sheets
foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
{
//Selecting the worksheet where we want to perform action
ExcelWorksheet.Select(Type.Missing);
ExcelWorksheet.Columns[1].NumberFormat = "#";
}
//saving excel file using Interop
ExcelWorkbook.Save();
//closing file and releasing resources
ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(ExcelWorkbook);
ExcelApp.Quit();
Marshal.FinalReleaseComObject(ExcelApp);
You need to format the column to be a string.
You can use the link https://supportcenter.devexpress.com/ticket/details/t679279/import-from-excel-to-gridview
For converting the ExcelDataSource, you can also refer to https://supportcenter.devexpress.com/ticket/details/t468253/how-to-convert-exceldatasource-to-datatable

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.

Leading 0 is dropped from excel data cells populated from VB

In my vb Windows Application Program I use this code to create excel report:
Public Sub CreateExcelFile(ByVal InputDataTable As DataTable, ByVal FileName As String)
Dim ExcelApp As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim ExcelWorkbook As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim ExcelWorkSheet As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim ColumnIndex As Integer = 0
Dim RowIndex As Integer = 1
Try
ExcelWorkbook = ExcelApp.Workbooks.Add()
ExcelWorkSheet = ExcelWorkbook.ActiveSheet()
For Each c As DataColumn In InputDataTable.Columns
ColumnIndex += 1
ExcelApp.Cells(RowIndex, ColumnIndex) = c.ColumnName
Next
For Each r As DataRow In InputDataTable.Rows
RowIndex += 1
ColumnIndex = 0
For Each c As DataColumn In InputDataTable.Columns
ColumnIndex += 1
ExcelApp.Cells(RowIndex, ColumnIndex) = r(c.ColumnName).ToString
Next
Next
ExcelWorkSheet.Columns.AutoFit()
ExcelWorkbook.SaveAs(FileName)
ExcelWorkbook.Close()
ExcelApp.Quit()
Catch ex As Exception
MsgBox("Err", MsgBoxStyle.Information + MsgBoxStyle.MsgBoxRtlReading)
Finally
ExcelApp = Nothing
ExcelWorkbook = Nothing
ExcelWorkSheet = Nothing
ColumnIndex = Nothing
RowIndex = Nothing
End Try
End Sub
if I have a code or telephone number that has a 0 as the first character, it does not show in excel file . I use this code to solve the problem:
ExcelWorkSheet.Activate()
ExcelWorkSheet.Cells().Columns.NumberFormat = "#"
ExcelWorkSheet.Cells().EntireColumn.NumberFormat = "#"
but it doesn't work. I read this question but cannot solve my problem:
Format an Excel column (or cell) as Text in C#?
Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c#
Insert DataTable into Excel Using Microsoft Access Database Engine via OleDb
Setting the format of a cell after you have data in it does not always work because some data may have been lost on entry in the conversion to the original data format. Make sure you set the format of the cell first so that any leading zeros do not get truncated.

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