gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:18:51 26 4
gpt4 key购买 nike

有没有办法在导出到 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"); 将返回您的日期。

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

Date Settings

默认情况下,这将使您的日期在计算机上的 Excel 上按照您想要的方式显示,但在不同计算机上的显示方式会有所不同。

关于c# - 导出到 Excel 中的 yyyy-MM-dd 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11629472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com