Get excel cell's value as text epplus? - c#

I have a excel file with a column with format like this
when i tried to get cell value by
var v = cell.Value;
it return Double, so how can i get value as text ?

Cast the cell value back to a DateTime object. Then you can format it any way you want.
DateTime date = DateTime.FromOADate((double)cell.Value);
string dateFormatted = date.ToLongDateString();

Related

C# DateTime from Excel turns into float number

I have an excel file in the first column which contains dates in the format dd.MM.yyyy hh:mm:ss. I'm trying to display data from an excel table in datagridview, but the date is displayed as a float number.
I tried to convert the date to the desired format in this way, but it does not work:
worksheet.Cells[2, 1, endCell.Row, 1].Style.Numberformat.Format = "dd.MM.yyyy hh:mm:ss";
The full code of my method:
public static DataTable readTableFromExcel(FileInfo file)
{
DataTable table = new DataTable();
Console.WriteLine(file.Exists);
using (ExcelPackage package= new ExcelPackage(file))
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
ExcelCellAddress startCell = worksheet.Dimension.Start;
ExcelCellAddress endCell = worksheet.Dimension.End;
ExcelRange range = worksheet.Cells[startCell.Row, startCell.Column, endCell.Row, endCell.Column];
ExcelTable excelTable = worksheet.Tables.Add(range, "table");
Console.WriteLine(worksheet.Cells[2, 1].Value.ToString());
table = excelTable.ToDataTable();
}
return table;
}
String with Console.Writeline outputs 44912,0912268519 instead of 17.12.2022 2:11:22.
Then I output the data to datagridview: tableView.DataSource = table;
And it looks like: https://i.stack.imgur.com/aXx6V.png
File used: https://drive.google.com/drive/folders/1hXKmKs_F7EyO5GdVU3HVATxDLlFWO4jk?usp=share_link
How can I display the datetime correctly?
In Excel, dates and times are stored as a floating point number representing the number of days since the epoch date of January 1, 1970. This means that when you read a date or time value from an Excel file into a C# DateTime object, you will need to convert the floating point value to a DateTime object.
// Assume that the Excel date value is stored in a variable called "excelDate"
// Convert the Excel date value to a DateTime object
DateTime dateTime = DateTime.FromOADate(excelDate);
system.datetime.fromoadate

Custom date format in Excel for zero

I am new to excel and C#. I am fetching data from database and showing in excel. In a array when ever there is a null record I am replacing it with '0'. My issue is after I format the column to a date format '0' is replaced by default value '1/0/1900'. I need a custom format which will format only date records and but not zeros.
Note:In below Code Data= contains array of records. CreateDataArray will check for null records and will replace by 0.
object[,] updateValues = CreateDataArray(data, 1, direction);
IRange dataRange = _rangeHelper.GetRangeBeside(startCell, data.Length - 1, direction);
dataRange.Value2 = updateValues;
// Apply format
dataRange.NumberFormat = "m/d/yyyy";
dataRange.NumberFormatLocal = "m/d/yyyy";
Try this:
dataRange.NumberFormat = "m/d/yyyy;;#0";

Get cell format to check date column value in excel using opemxml SDK

value = string.Empty;
if (cell.StyleIndex != null)
{
CellFormat cf = document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ChildElements[int.Parse(cell.StyleIndex.InnerText)] as CellFormat;
if (cf.NumberFormatId == 14)
{
//value = DateTime.Parse("1900-01-01").AddDays(int.Parse(cell.CellValue.Text) - 2).ToString("yyyy-MM-dd");
value = Convert.ToString(DateTime.FromOADate(Double.Parse(cell.CellValue.Text)).ToShortDateString());
}
if (cf.NumberFormatId == 176 || cf.NumberFormatId == 177)
{
//value = DateTime.Parse("1900-01-01").AddDays(int.Parse(cell.CellValue.Text) - 2).ToString("yyyy-MM-dd");
value = Convert.ToString(DateTime.FromOADate(Double.Parse(cell.CellValue.Text)));
}
}
I am using the above code to check if there is any date column in excel and then convert the value of the cell to equivalent date.By default the NumberFormatID is 14,but there are more date formats in excel.For a particular date format sometimes the NumberFormatID is 165 and sometimes it is showing 176.
These are not fixed.So when i am selecting the date time format sometimes it is 176 and sometimes it is different so my code is not working.How do i differentiate a particular date and datetime format?
Like you say, there is a lot of "dateformat", and people can custom the field (I don't know if it's the case for you).
If your only problematic is "parsing a date", simply use DateTime.TryParse
value = string.Empty;
if (cell.StyleIndex != null)
{
DateTime res;
if (DateTime.TryParse(cell.CellValue.Text, out res))
{
value = res.ToString("yyyy-MM-dd");
}
}
If the cell is in a "date format", TryParse will succeed

Select query to get the any format of datetime value from the Excel file

I am using the below select query to get the details from excel sheet.
Select UserID,UserName,Country,State,City,DOB from [Sheet1$]
By default DOB(DateOfBirth) value is mm/dd/yyyy format in Excel file.
If i changed the DOB value format mm/dd/yyyy to dd/mm/yyy or d-m-yyyy (other than deafult format)in the excel.The above select query retriving the empty DOB value.
How to write the select query to get the any format of datetime values?
If there is any method similar to Cast() or Convert() in SQL,Let me know
in order to GET universal value - you should SET a universal value.
here is an example :
05/22/1978
there are more pattrens.
but here is a code which you might find easy to use :
if (value != null)
{
if (value is double)
{
dt = DateTime.FromOADate((double)value);
}
else
{
DateTime.TryParse((string)value, out dt); //here you can try patterns of dd/mm/yyyy
}
}
Try this. Don't waste your time with casts. Simply fetch the value you need, and then have String.Format display it in the format you need it to be displayed in.
Query the normal DoB value (like in your format mm/dd/yyyy), and where you display it, use String.Format( {0:dd/MM/yyyy},DOB );
Hope this helps
For instance, after you have your dataset with the results in it,
string DateOfBirth = String.Format ( {0:dd/MM/yyyy},<yourDataSet>.Tables[0].Rows.Field<string>(column_number));

Replacing a DateTime.MinValue in a DataGridView

I am working on a name record application and the information is stored in a SQLite database. All columns in the database are TEXT types, except for the date of birth column, which is a DATETIME. The original Access database that I transferred to the SQLite database allowed nulls for the date of birth, so when I copied it over, I set all nulls to DateTime.MinValue.
In my application, the date of birth column is formatted like so:
DataGridViewTextBoxColumn dateOfBirth = new DataGridViewTextBoxColumn();
dateOfBirth.HeaderText = "DOB";
dateOfBirth.DataPropertyName = "DateOfBirth";
dateOfBirth.Width = 75;
dateOfBirth.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";
My problem is that rows where there is not a date of birth, the database has DateTime.MinValue, which displays in my DataGridView as 01/01/0001.
I am looking for a way to replace the 01/01/0001 with an empty string ("") in my DataGridView.
private void resultsGrid_DateFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if(resultsGrid.Columns[e.ColumnIndex].Name.Equals("DateOfBirth"))
{
if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
{
// Set cell value to ""
}
}
}
Anyone have an idea how I can replace a DateTime.MinValue in my DataGridView with an empty string? Thanks!
Edit: Casting the cell value with DateTime allows the if statement I have to work, but I am still not able to figure out the coding to replace the MinValues with a blank string.
You just need to cast it to DateTime
if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
{
// Set cell value to ""
}
I discovered why the DateTime.MinValue was displaying!
This line in the cell formatting section caused the MinValue of "01/01/0001" to display:
dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";
Without this line, the Date of Birth field in my datagridview is left blank.
Barbaros Alp is still correct about what I was trying to do at the time. Thanks everyone!
Use nullabe DateTime format instead of DateTime ("DateTime?") - don't use string.
example:
public DateTime? mydate;
and then:
DGview.Rows.Add(mydate.HasValue ? mydate : null);
While it may be quite straightforward to achieve the transformation you need (see the excellent answers preceding mine), I feel that you should ideally replace all the DateTime.MinValue values in this particular column in the database with NULL. This would correctly represent the actual lack of data in this position. At present your database contains incorrect data and you are trying to post-process the data for display.
Consequently, you would be able to handle the display of data in your GridView using the EmptyDataText or NullDisplayText properties to provide appropriate rendering.
if (yourDateOfBirth != null)
{
Convert.ToDate(yourDateOfBirth) == DateTime.MinValue
}
you can cast the object as a DateTime object:
//create a nullable intermediate variable
System.DateTime? dtCellValue = resultsGrid.CurrentRow.Cells["DateOfBirth"].Value as System.DateTime?;
//if this cell has been set to String.Emtpy the cast will fail
//so ensure the intermediate variable isn't null
if ( dtCellValue.HasValue && dtCellValue == System.DateTime.MinValue )
//set cell value appropriately
private void resultsGrid_DateFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if(resultsGrid.Columns[e.ColumnIndex].Name.Equals("DateOfBirth"))
{
if ((string)resultsGrid.CurrentRow.Cells["DateOfBirth"].Value == DateTime.MinValue.ToString())
{
// Set cell value to ""
}
}
}
Or you might have to cast to DateTime and then compare to MinValue, but it sounds like you have the right idea.
There are already answers that should achieve what you want; but I wonder why you don't put NULL in the database to start with? In sqlite3, "datetime" is more or less just a string, (there is nothing special about a datetime column since sqlite3 is all about just type afinity, not type binding), so you just insert NULL in that column. And in case you want to have the MinValue of datetime when you query, you can easily execute a query like
select coalesce(your_datetime_column,'01/01/0001') from your_table

Categories

Resources