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"
Related
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#?
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
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 have created a program which converts an Excel worksheet into a text file. I load the whole of the worksheet into an array then loop through it and write out the columns I need. Some of the columns are dates.
My issues are some dates are e.g. 06/09/2014 but are being output as 09/06/2014. I have formatted the dates using CultureInfo("en-GB") when I read it from the array. Is this not the right way?
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.