سؤال

The datetime I'm writing to Excel always get rounded up to the next day:

workSheet.Cells[0, 0] = new Cell(DateTime.Now, new CellFormat(CellFormatType.DateTime, @"HH:mm:ss"));

In the output Excel file the cell gets this value: 29/09/2013 00:00:00

The DateTime.Now from this example is 28/09/2013 19:42:23

هل كانت مفيدة؟

المحلول

I ended up passing the cell value as a string instead of as a DateTime:

 workSheet.Cells[0, 0] = new Cell(DateTime.Now.ToString(@"HH:mm:ss:ff"),
                                  new CellFormat(CellFormatType.DateTime, @"HH:mm:ss"));

نصائح أخرى

If you are using the ExcelLibrary Project Source Code, you can fix this by:

  1. Go to SharedResource Class in this location: [Project Source Code folder]\Office\BinaryFileFormat folder

  2. Change the EncodeDateTime function as below:

    public double EncodeDateTime(DateTime value)
    {
        double days = (value - BaseDate).Days;
        //if (days > 365) days++;
        return days;
    }
    
  3. Pass the DataTime object to the Cell with the prefered format:

    worksheet.Cells[iIndex, j] = new Cell(((DateTime)cellValue), new CellFormat(CellFormatType.DateTime, @"dd/MM/yyyy"));
    

You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.

If oCell.Format.FormatType = CellFormatType.Date OrElse oCell.Format.FormatType = CellFormatType.DateTime Then
 Dim d As Double = Double.Parse(oCell.Value)

 Debug.print(DateTime.FromOADate(d))

End If
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top