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.
Related
Using C# to replace an existing and now defunct legacy routine in Delphi, I’ve been trying re-develop a routine in C# that worked well in Delphi 7 that will open each of my 30 Excel files, select the last 22 rows in each, copy them, and reinsert them back into their respective files.
For example, I find the last row, August of 2019 has 22 business days so I begin my range 22 rows back from the last row.
Using the Excel file, I want to select the rows that range from A4157 to A4178. Then, I want to take the rows I’ve copied and insert them after row A4156 or before row A4157. I then take a separate list of August dates and write them to each of the lower 22 from A4178 to A4200. July is then complete and rows for August are ready to go.
I retain the last row because additional calculations on other worksheets in the same workbook refer to the last row for data and they will index automatically from A4178 to A4200 doing it this way.
As each entry made during the month, its data are copied down to the last row so the last row is always up to date. Another sheet in the workbook uses up-to-date data in its summary.
So far, I can open the Excel workbook and get the right sheet.
The following does highlight the proper row but I get a runtime error. I’m not sure what that means.
I’ve commented out the “select” line and run the “copy” line with the same result. I’m now into my second week trying to work out this problem. I need an example of a functioning routine if possible. A link to a text on C# - MS interfacing would be a great help.
Excel.Range selectRange = excelWorkSheet.Range[excelWorkSheet.Cells[A4157], excelWorkSheet.Cells[A4178].select;
Excel.Range copyRange = excelWorkSheet.Range[excelWorkSheet.Cells[A4157], excelWorkSheet.Cells[A4178]].select;
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot implicitly convert type 'bool' to 'Microsoft.Office.Interop.Excel.Range''
I'm not 100% clear on what you want in your final worksheet. But I think you're trying to do something like this.
// In your example startRow = 4157 and lastRow = 4178.
// Get the rows to copy (rows 4157 to 4178 in your example).
Excel.Range copyRange = excelWorkSheet.Rows[startRow + ":" + lastRow];
// Insert enough new rows to fit the rows we're copying.
copyRange.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
// The copied data will be put in the same place (starting at row 4157 in
// your example).
Excel.Range dest = excelWorkSheet.Rows[startRow + ":" + lastRow];
copyRange.Copy(dest);
Take a look at Epplus. https://github.com/JanKallman/EPPlus. It's available as a Nuget package.
There is a tutorial in the Github Wiki and a sample app that exercises many of the features.
I am exporting a DataSet to excel that was generated by running an SQL script within my C# program. The DataSet correctly stores certain columns as datetimes, but from my understanding it does not store formatting information. It appears then that the formatting is given when call
ws.FirstCell().InsertTable(dt, false);
Which gives it the default format dd/mm/yyyy. Unfortunately I can't just select the whole range with ClosedXML and change the number format since come columns contain non-date numbers.
I suppose I could probably go through my data set, find which columns are date times, and format those columns accordingly with closedXML. I would imagine there has to be a better way though. Does anyone know an easy option for doing this with closed XML (or interop even)? I was unable to find anything on this.
EDIT:
Appears this is the only way at the moment... if anyone needs it (and manages to find this post) its easy enough to do:
//select which columns are dates and change default format
int colNum = 1;
foreach (DataColumn col in dt.Columns)
{
if (col.DataType == typeof(System.DateTime))
{
Console.WriteLine(colNum);
ws.Column(colNum).Style.NumberFormat.Format = "mmm-dd-yyyy";
}
colNum++;
}
ws.FirstCell().InsertTable(dt, false);
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 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
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.