How to make correct date format when writing data to Excel

后端 未结 10 1875
[愿得一人]
[愿得一人] 2020-11-30 04:56

Iam exporting a DataTable to an Excel-file using office interop. The problem is, that Excel does not recognize dates as such, but instead it displays numbers. In another cas

相关标签:
10条回答
  • To format by code Date in Excel cells try this:

    Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];
    
    rg.NumberFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
    

    After this you can set the DateTime value to specific cell

    xlWorkSheet.Cells[numberRow, numberColumn] = myDate;
    

    If you want to set entire column try this: Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];

    rg.EntireColumn.NumberFormat = 
        CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
    
    0 讨论(0)
  • 2020-11-30 05:19

    Try using

    DateTime.ToOADate()
    

    And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.

    Hope this helps.

    0 讨论(0)
  • 2020-11-30 05:27

    Hope this help

    private bool isDate(Range cell)
        {
            if (cell.NumberFormat.ToString().Contains("/yy"))
            {
                return true;
            }
            return false;
        }
    
    isDate(worksheet.Cells[irow, icol])
    
    0 讨论(0)
  • 2020-11-30 05:28

    Try this solution, in my softwarew work very well:

    if (obj != null)
    {
        if (obj is DateTime)
        {
            if (DateTime.MinValue == ((DateTime)obj))
            {
    
                xlWorkSheet.Cells[x,y] = String.Empty;
    
            }
            else
            {
    
                dynamic opp = ((DateTime)obj);
                xlWorkSheet.Cells[x,y] = (DateTime)opp;
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题