Excel worksheet in c# array date Issues - c#

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?

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"

C# exporting to Excel format invalid

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#?

How to properly read dates from a csv / excel file

I have a CSV file that needs to be opened in excel. I want to read an entire row at a time into my program and store it in some kind of list or array. In past projects I have used:
DateTime[] dates = xlworksheet.get_Range("B7", "B"+xlWorksheet.Rows.Count);
This is giving me the error: "Cannot convert type 'object[,]' to 'System.DateTime[]'". This makes sense but I don't know how to store the entire column other wise. How do I read an entire column from an excel worksheet into a list/array in my program?
I am assuming you are using .NET 3.5 or higher. Add a using System.Linq;
DateTime[] dates = xlworksheet.get_Range("B7", "B"+xlWorksheet.Rows.Count).Cast<DateTime>().ToArray();

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