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.
Related
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"
I am trying to export datagrid's data to an excel sheet in C#. Using below code I managed to export it successfully
private void ExportToExcelAndCsv()
{
dataGrid.SelectAllCells();
dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dataGrid);
String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result = (string)Clipboard.GetData(DataFormats.Text);
dataGrid.UnselectAllCells();
System.IO.StreamWriter file1 = new System.IO.StreamWriter(#"C:\Users\Fisniku\Desktop\"+tipiL+".xls");
file1.WriteLine(result.Replace(',', ' '));
file1.Close();
}
My issue is that I have a column in String datatype in SQLServer containing data in format of fractions such as:
1/2
2/2
1/3
9/4
When data is exported in excel, that column becomes a date, and shows data like a date 01-Jan in Custom format.
After trying to modify the column in excel to text format, it looses value and becomes invalid.
How can I modify the code so it will preserve the same format as in datagrid?
I am assuming that this data in the grid originates from a SQL query or table based on the tags on your question. If that's the case, and if either the data is read-only or the data is in a datatable that is bound to the grid, then an easy way of accomplishing this is to use EPPlus instead of interop.
EPPlus has a single command to export a C# datatable (System.Data.DataTable) into a spreadsheet:
ws.Cells["A1"].LoadFromDataTable(dt, true);
And, per your original problem, it respects datatypes meaning it won't clobber leading zeroes on text fields that have all numbers, convert text that looks like a date into a date, etc.
If you're not using a datatable, you can always convert your content to a datatable (although there is a lot of overhead with this approach).
If you are married to interop, then just be sure you format the appropriate columns as text BEFORE you do the paste:
sheet.Range["A:A"].NumberFormat = "#";
You may need to format the cell as text. Take a look at this question:
Format an Excel column (or cell) as Text in C#?
I am dumping a string Date from DataTable to Epplus. I want to treat that date as Date in Excel. So that I can get Date Filter in Excel.
Things I tried,
Passed that date as Datetime. Now, Excel takes it as date and gets a date filter. But, it affects the pivot
Passed it as string with req. date format, The excel takes it as string and does not gets the date Filter in excel.
Hope i will get a solution from you guys. Any help will be appreciated.
You can use Numberformat property.
If you want set for whole column then you can apply it following way
ws.Column(1).Style.Numberformat.Format = "yyyy-MM-dd";
Or for particular cell
ws.Cells["A3"].Style.Numberformat.Format = "yyyy-MM-dd";
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);
}
I am using oledb to read data from an excel file and store it in a dataset.
My excel file contents are like as follows:
0 0 somestring somestring
500 200 somestring somestring
When i checked the contents of my data set, the values of Columns 1 & 2 are not stored as integers but rather as DateTime values.
How will I make it be stored as integer values instead of DateTime?
Have you tried adding IMEX=1 to your OLEDB connection string?
Are you sure its a number? Following could be a few options:
Right click the columns in excel and change the format to Text/Custom.
Look into the NamedRange.FormatConditions Property; change the format the data when you read it from excel, see MSDN
Or try deleting an existing format on a range:
that is,
Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", "A5") as Excel.Range;
//delete previous validation rules
range.Validation.Delete();
You could use a 3rd party component like SpreadsheetGear for .NET which lets you get the underlying values of cells (with IWorkbook.Worksheets["MySheet"].Cells[rowIndex, colIndex].Value) regardless of the cell format, or you can get the formatted result with IRange.Text.
You can see live ASP.NET samples here and download the free trial here.
Disclaimer: I won SpreadsheetGear LLC