C# : Error Printing the Date Value in Excel - c#

I am building a winform based Desktop application. As part of the application, I am generating the Excel output.
I am getting a error, when I am trying to enter the date value.
In C#, the date value is "11-10-12". However, in Excel, it is printing as 10-11-2012.
Here is the code, which does it :
String Date1 = "11-10-12";
oSheet.Cells[i + 2, 1] = DateTime.ParseExact(Date1, "dd-MM-yy", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Any idea what could could be wrong ?
EDIT
The Cell format in Excel was by default General. However, when the values are entered, it is changed to Date.

Try changing the format of the excel-Cell with:
yourCellRange.NumberFormat = "dd-MM-yy";
or adjust the string format to the excel-format.

Try doing this
worksheet.get_Range(Cell1, Cell2 + worksheet.Rows.Count).NumberFormat = "dd-mmm-yyyy";
When you are adding the value you can try
worksheet.Cells[row, column] = String.Format("{0:dd-MMM-yyyy}", Date1);

None of the suggestion helped unfortunately. So, I disabled the automatic formatting in Excel :
So, here is the code snippet which disables the automatic (Date) formatting in Excel :
String Date1 = "11-10-12";
oSheet.Cells[i + 2, 1] = "'" + Date1;
So, the trick is to preceed the String with an apostrophe which worked.
Thanks

Try just:
DateTime.Now.ToString("dd-MM-yy");
or:
String Date1 = "11-10-12";
var Format = "dd-MM-yy";
var TimeBuff = DateTime.ParseExact(Date1, Format,
CultureInfo.InvariantCulture).ToString(Format);
oSheet.Cells[i + 2, 1] = TimeBuff;
Both Parse and ToString must contains the same Format. If you get the same its definitely a Excel failure.
Edit:
Just for DJ KRAZE

Related

Excel does not work the sum in the status bar for a file generated in C#

In Excel does not work the sum in the status bar for a file generated in C#. In the code I set the cell format as a number. Any idea what might be going on?
My code:
oWorksheet.Cells[vLinhaCelula, 7].NumberFormat = "0";
oWorksheet.Cells[vLinhaCelula, 7].Value = vValorNF.Replace(".", "");
oWorksheet.Cells[vLinhaCelula, 7].HorizontalAlignment = XlHAlign.xlHAlignRight;
Thanks for any help.
My guess is that vValorNF.Replace(".", ""); is returning a string, and therefore the cell becomes a string regardless of the number formatting. Try specifically creating a double or decimal
double num = Double.Parse(vValorNF.Replace(".", ""));
and then assigning
oWorksheet.Cells[vLinhaCelula, 7].Value = num;

I am having trouble formating the date in the excel sheet I am reading from using C#

/* all of these are output fields that are being parsed with input fields from an excel*/
public void Import()
{
CRMRecord r;
DataTable dtCarrierData = LoadXL(true);
foreach (DataRow dr in dtCarrierData.Rows)
{
r = new CRMRecord();
r.FleetID = "TN045";
r.BillingCompany = "TCH";
r.StationCode = ParseField<string>(dr, "fp_truckstopcode");
r.DriverID = ParseField<string>(dr, "FP_unitnumber");
r.TransactionDate = ParseField<string>(dr, "FP_transdate"); /* I have a standard output and transaction date = FP_Transdate basically but the trouble is the FP_transdate format coming in as "yyddMM" Ex:210120, 210121, there are 5 more just like those in the column (FP_transdate) */
DateTime FP_transdate = DateTime.ParseExact("yyddMM", "MM/dd/yyyy", CultureInfo.InvariantCulture); /* here is where I have an output that is reading an excel everything is reading fine except for date, i get an error saying "Processing exception - String was not recognized as a valid DateTime." It is not formatted correctly in the input(its "yy/dd/MM", I need it to be "MM/dd/yyyy" and it comes from an outside source so I can't just change the cell value in excel to date. */
FP_transdate.ToString("MM/dd/yyyy");
r.Ref1 = ParseField<string>(dr, "FP_truckstopinvnum");
decimal trcFuelCost = ParseField<decimal>(dr, "trcFuelCost");
decimal reefFuelCost = ParseField<decimal>(dr, "reefFuelCost");
I have figured it out.
r.TransactionDate = ParseField(dr, "FP_transdate").Substring(2, 2) + "/" + ParseField(dr, "FP_transdate").Substring(4, 2) + "/" + "20" + ParseField(dr, "FP_transdate").Substring(0, 2);
There may be a better way to write this but this worked for me.

how to change the formatting of chart legends

I want to set a number format of the lengends on a chart with the next format:
300.000 kWh
Actually i get 300000.
How can i do this.
I tried do it manually with Excel setting the format of the cell to personalized number format in the dialog cell Format adding this format # "kWh".
With this trick, I can do. But I need to do this when I generate the excel, and not when the excel is generated...
cells["kwhcell"].Style.NumberFormat = "#.##0,00 kWh";
You can't directly. You'll have to loop all the cells and do the formatting yourself.
for (int i = 1; i <= excelWorksheet.Dimension.End.Row; i++)
{
string cellValue = string.Format("{0:N2}", Convert.ToDecimal(excelWorksheet.Cells[i, 1].Value)) + " kWh";
excelWorksheet.Cells[i, 1].Value = cellValue;
}
I sloved my Problem.
This is the correct code to answer my question
wsData.Cells[2, (z + 1)].Style.Numberformat.Format = "#0,0 \"kwh\"";
and
wsData.Cells[2, (z + 1)].Style.Numberformat.Format = "#0,0 \"ÂșC\"";

C#: How to add formula to Excel through C# Code. Getting invalid Formula error

Column 'I' have To date
Column 'H' have From date
I want to calculate difference between two date and store it in column 'J'.
Formula to do this is "=DATEDIF(I18,H18,"d")"
I am getting below error if i execute below code.
Error: Invalid formula.
ArgumentException was unhandled by user code.
private void FillExcelCellFormula(IRange cell, int row, int column, object content)
{
string row1 = "I" + Convert.ToString(row);
string row2 = "H" + Convert.ToString(row);
string dquote = #"""d""";
string daysFormula = "=DATEDIF(" + row1 + "," + row2 + "," + dquote + ")";
cell.FormulaR1C1 = daysFormula;
}
Formula value getting poppulated in daysFormula = "=DATEDIF(I18,H18,\"d\")"
Although i am not sure if the '\' is the reason behind the error.
Even a simple sum function is not working. I replaced the formula to a simpler formula like,
string daysFormula = "=SUM(A18:B18)";
yet i am getting same error.
Do i have to call for any library?
Any suggestions?
I would recommend checking the To & From dates.
What format are they stored in, in your Excel file ?
If they are stored as string, this might cause the error. Dates need to be stored as integers, with styling applying to display them as dates.
Update
Btw, dumb question: What happens if you use Formula rather than FormulaR1C1:
cell.Formula = daysFormula;

How can i change the text format of a Excel Cell using C#?

I am currently writing an application (C#) to generate reports in a excel file, based on other reports.
The problem is that, once get an number from a certain sheet, and copy to another one, the destination cell is not formated correctly, and the number does no display correctly.
E.g :
Number from source : 14.34
Number on destination : 14.345661
How do i format the destination cell to force the number formating to be the same as the source cell.
Thanks !
The format of a given cell/range in excel can be set via code.
public void SetCustomFormat(string format, int r, int c)
{
((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}
In your specific case, I believe you would need to use the format "#.00" or "#.##"
Here's a snippet from some code I've got in use, to show you the general pattern for formatting cells. Obviously, there are some variables declared, but it should show you what you need.
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Font.Bold = true;
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Interior.Color = Color.Silver.ToArgb();
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
sheet.get_Range("A" + CompetencyStartRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
That first line, assuming CurrentRowIndex = 1 and ColPrefix = "B", replacing the variables with the resulting values would translate into
sheet.get_Range("A1", "B1").Font.Bold = true;
At any rate, you want to set the numberformat. (Coming..)
sheet.Cells[Row, Column].NumberFormat = "0.00"

Categories

Resources