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

有没有办法在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); 

编辑:

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

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

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

如果您打开一个新的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;@"; 

但我没有测试过它

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

 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); } } } 

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

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

日期设置

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

这是我的代码,我通过以下代码实现:

  Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; Microsoft.Office.Interop.Excel.Range excelRange; excelRange = worksheet.get_Range("H2", System.Reflection.Missing.Value); excelRange.NumberFormat = "yyyy-MM-dd;@";