导出到Excel中的yyyy-MM-dd日期格式

kk1*_*076 2 c# asp.net date-format export-to-excel openxml-sdk

有没有办法在Export to Excel函数中使用此功能从UniversalSortableDateTimePattern单独获取日期.Excel不接受日期格式..
我需要显示为yyyy-MM-dd.任何建议都会有所帮助吗?我的代码为

 dtASalesDrivers.Columns.Add(new System.Data.DataColumn("Start Date", typeof(String)));
DateTime dt = Convert.ToDateTime(txtATrendStartDate.Text);
 drASalesDrivers[2] = string.Format("{0:yyyy-MM-dd}", dt);
dtASalesDrivers.Rows.Add(drASalesDrivers);
Run Code Online (Sandbox Code Playgroud)

编辑:

            DateTime dt = Convert.ToDateTime(txtATrendStartDate.Text);
            drASalesDrivers[2] = string.Format("{0:u}", dt);
Run Code Online (Sandbox Code Playgroud)

这会显示日期和时间.有没有办法只显示日期???

JMK*_*JMK 5

我认为这与您的计算机设置有关.

如果您打开一个新的Excel实例并键入2012-07-24并离开单元格,它将立即更改为24/07/2012,它是您的计算机区域设置,而不是与您的代码有关的任何内容.

但是,您可以格式化单元格,yyyy-mm-dd;@以便您可能需要以编程方式执行此操作而不更改其他任何内容,我认为这可能有效:

DateTime dt = Convert.ToDateTime(txtATrendStartDate.Text);
drASalesDrivers[2] = string.Format("{0:u}", dt);
drASalesDrivers[2].NumberFormat = "yyyy-mm-dd;@";
Run Code Online (Sandbox Code Playgroud)

但我没有测试过它

我正在做一些搞乱,下面是一些示例代码:

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            Application _excelApp = new Application();
            Workbook workbook = _excelApp.Workbooks.Open(@"C:\test\New Microsoft Excel Worksheet.xlsx");

            Worksheet sheet = (Worksheet)workbook.Sheets[1];
            Range excelRange = sheet.get_Range("A1");

            //If you comment the next line of code, you get '24/07/2012', if not you get '2012-07-24'
            excelRange.NumberFormat = "yyyy-mm-dd;@";

            excelRange.Value2 = "2012-07-13";

            workbook.Save();
            workbook.Close(false, @"C:\test\New Microsoft Excel Worksheet.xlsx", null);
            Marshal.ReleaseComObject(workbook);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,string.Format("{0:u}", dt);确实会返回一个日期和时间,dt.ToString("yyyy-MM-dd");将返回您的日期.

另外一种方法是将Short date您的计算机设置更改为yyy-MM-dd,如下所示:

日期设置

这将使您的日期在计算机上默认显示在Excel上,但在不同的计算机上看起来会有所不同.