gpt4 book ai didi

c# - 在 C# 中从 DataGrid 导出到 Excel 时停止日期自动格式化

转载 作者:太空宇宙 更新时间:2023-11-03 19:31:52 24 4
gpt4 key购买 nike

我目前正在为从数据集/数据网格导出的特定 Excel 文件格式化日期。
日期格式如下:

DateTime date = Convert.ToDateTime(entry.Date);
string formatdate = String.Format("{0:yyyy/MM/dd}", date);

创建 DataSet 后,我​​使用以下代码将 DataSet 导出到 Excel 文件:

public static void ExportDStoExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";

response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}

}

我唯一的问题是一旦我将其导出到 Excel,Excel 会像这样自动格式化日期:MM/DD/YYYY 而不是 YYYY/MM/DD。

我知道这可以通过在 Excel 中打开来手动实现,但导出正在构建到一个自动化系统中,需要进行硬编码。

有什么方法可以绕过 Excel 的日期时间自动格式化?

最佳答案

我遇到了同样的问题,通过在文本前面添加一个不间断空格 ( ) 解决了这个问题。停止 Excel 自动格式化。不是最干净的解决方案,但对我有用......

关于c# - 在 C# 中从 DataGrid 导出到 Excel 时停止日期自动格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413471/

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