Incorrect date formating in Excel worksheet - c#

I'm working on a Excel AddIn, that include an Excel workbook as template.
In all the worksheets of this workbook, the date is correctly formatted (I mean, I type 01/01/2013, and it displays 01/01/2013). But in only one worksheet of the workbook, the date isn't displayed correctly. I type 01/01/2013, and it displays 41275. And when I select this cell, the cell still displays 41275, but the formula area displays the correct date, i-e 01/01/2013.
Some precisions:
Using Excel 2010, 32bits, in English (I know sometimes locale might influence the formula).
The formating of the cells is the same (right click -> Format cells ... is type of Date for all the cells, in all the worksheets).
I'm doing some modifications with this AddIn, using C# and the Component Object Model, but the modifications are the same for the entire Workbook (nothing specific to a worksheet).
Any ideas/clues where it could come from ? And how to fix it ?
Thanks in advance !!

You may use this snippit to convert from excel serial date format
protected static DateTime FromExcelSerialDate(int serialDate)
{
if (serialDate > 59) serialDate -= 1; //Excel/Lotus 2/29/1900 bug
return new DateTime(1899, 12, 31).AddDays(serialDate);
}

Related

EPPLUS preserve date format when saving CSV

I am using EPPLUS to create a csv file. When I create an Excel file, I can format the date thus:
ws.Cells["A:A"].Style.Numberformat.Format = "yyyy-MMM-dd";
Which is what I need in my csv. However, if I try to save the worksheet as a csv, any dates end up as numbers.
***EDIT - I appreciate Excel stores the date as a serial number, I was just wondering if EPPLUS had a feature I can't locate to help me out.
Assuming you are setting the value to a proper DateTime value in code, you should be able to use the Text property of the cell like this:
var ws = package.Workbook.Worksheets.Add("Test");
ws.Cells["A:A"].Style.Numberformat.Format = "yyyy-MMM-dd";
ws.Cells["A1"].Value = DateTime.Now;
Console.WriteLine(ws.Cells["A1"].Text); // "2022-May-26"

Current Format of excel getting changed in Closedxml SaveAs method

In my C# application, I am using ClosedXml .Excel for working with excel files.
I have an excel template, where I add the template into application and add data to the excel sheet and save the excel as below,
wb = new XLWorkbook(exportOption.FileName);
---
if (wb.Worksheets.Count > 0)
{
for (int i = 0; i < wb.Worksheets.Count; i++)
{
using (var ws = wb.Worksheet(i + 1))
{
if (ws.Visibility == XLWorksheetVisibility.Visible)
{
ws.SetTabActive();
break;
}
}
}
}
try
{
wb.CalculateMode = XLCalculateMode.Auto;
wb.SaveAs(exportOption.FileName);
}
After saving the changes my excel format completely changes with other sheets as well.
For example, In one sheet i have percentage format which changes to Date format.
How can i keep the format of excel same and just insert data to other sheets.
Its common for Excel to be tricked into treating numbers as dates (as under the hood Excel stores dates as numbers). To force the cell to be a number not date try:
ws.Cell(row,col).SetValue<double>(Convert.ToDouble(val));
Here is the official documentation on ClosedXML Cell Formatting.
If you need preserve the format as percentage, eg as "#.##%" simply set the cell format:
ws.Cell(row, col).Style.NumberFormat.NumberFormatId = 10;
or untested
ws.Cell(row, col).Style.NumberFormat.Format = "0.0%";
You must select the cell Number Format from your app before saving it.
CLosedXml is a library based on OPENXML library so you must apply an OpenXml excel style Sheet to change Cells Number Format.
This is an Article that may help you

Excel formating column for date and time

The program i'm doing now has me grabbing info from our database and exporting it to an Excel file. This is the first time I've done this so, sorry for the stupid questions (possibly).
I am having problems formatting the date/time.
The database has the date/time as : 9/19/2013 5:30:00 PM
However, whenever it is exported to the Excel file the cell shows : 9/19/2013 17:30
I just want the military time to go away.
You can apply whatever format you want to the excel cells manually at the end of the process, at the beginning by putting the data into a template or in code.
Also, you can link the spreadsheet directly to the data (subject to which RDMS you use), no program required!
If you aren't using custom formats directly in Excel then you can just write the data in your C# code using string formatters.
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.85).aspx

Inserting a Dictionary into a preexisting excel file, by date

The Data is stored in a Dictionary and arranged by month. (the string is what needs to be inserted.)
I have a preexisting excel file: it has all the dates of the year on the first column, and various entries in the following column. This data needs to be preserved.
My task is to basically insert the Dictionary into this excel file. What complicates things is that the Date value in the dictionary, needs to correspond to the date value in the excel column (date and month). To explicate: ("xxxx", 1980-05-12) needs to be inserted into the excel column with the first cell as "12-May" (this was generated via Fill->series).
And I have no idea. I'm spluttering by on bits of programming I'd picked up a couple of years ago. I've already extracted the data from the web page, and sorted it and all - automating some of the boring manual work. But I am faltering at the last mile, and seriously do not want to manually enter a couple of thousand data points when I know a simple script would suffice.
So, any help would be appreciated.
private void FindAndSetDate(WorkSheet ws, Dictionary<DateTime,string> dict)
{
Range find = null;
foreach(KeyValuePair<DateTime,String> kvp in Dict)
{
find = ws.Cells.Find(kvp.Key, Type.Missing,
Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false,
Type.Missing, Type.Missing);
if(find!=null) find.Offset[0,1].Value=kvp.Value;
}
}
take a look at this thread How to iterate through a column in an Excel application through C# Console?
If you have Excel installed you could use excel interop to fill the excel sheet. Formatting the date is easy with the DateTime string format options. In your case myDateTime.ToString("dd-MMM") would result in the desired format.

Problem with dates using CarlosAg.ExcelXmlWriter

I am using the CarlosAg.ExcelXmlWriter library to generate an Excel file in C#. If I treat all data as strings everything works fine, but I need some cells to be recognized by Excel as date fields. When I try to set the data type accordingly, the resulting Excel file fails to open in Excel 2003 (or Excel 2007 for that matter).
In Excel 2003, I get the following error on load:
Problems came up in the following area
during load: Table
I am using the following code to generate the DateTime cells that are causing the problem:
string val = DateTime.Now.ToString("MM/dd/yyyy");
row.Cells.Add(new WorksheetCell(val, DataType.DateTime));
Thanks.
I eventually figured this out. Thanks to Lance Roberts for nudging me in the right direction.
First, define a WorksheetStyle called dateStyle and set its NumberFormat property to a valid Excel date format:
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets.Add("myWorksheet");
WorksheetStyle dateStyle = book.Styles.Add("dateStyle");
dateStyle.NumberFormat = "Dd Mmm Yy";
WorksheetRow row = book.Worksheets[0].Table.Rows.Add();
Then, export the date using the .NET "s" date format and add the cell:
string val = DateTime.Now.ToString("s");
row.Cells.Add(val, DataType.DateTime, "dateStyle");
I haven't used his library, but work in Excel a lot. I don't know what he's doing with a datatype for a cell, since they don't work that way. Dates in Excel cells are all integers with Date Formatting.
I would try to put the date in as an integer, the trick is converting your string to the correct integer. See this link for information on Excel's Date as Numbers methodology. I would then set the WorksheetStyle.NumberFormat Property.

Categories

Resources