C#Winform如何在DataTable中设置日期格式?
我是C#的新手,我正在从事一个项目。
我得到了一个包含excel的DateTime的列,我将通过DataTable将数据输入到DataGridView中。
我在Excel中拥有的内容,例如:2022/05/29
,我想更改为特定格式,例如:20220529
我认为这应该很简单,但我只是无法正确。
我尝试过的是下面:
int col = 0;
for (int i = 0; i <= 23; i++)
{
DataRow row = dt_d.NewRow();
dt_d.BeginLoadData();
for (int j = 2; j <= 21; j++)
{
if (excelRange.Cells[j, i].Value != null)
{
if (i == 3)
{
DateTime date1 = (DateTime)excelRange.Cells[j, 3];
date1.ToString("yyyyMMdd");
}
if (i == 5)
{
DateTime date2 = (DateTime)excelRange.Cells[j, 5];
date2.ToString("yyyyMMdd");
}
if (i == 22)
{
DateTime date3 = (DateTime)excelRange.Cells[j, 22];
date3.ToString("yyyyMMdd");
}
row[col] = excelRange.Cells[i, j].Value.ToString();
}
}
col++;
dt_d.EndLoadData();
dt_d.Rows.Add(row);
}
执行它时,它给了我一个hresult:0x800A03EC例外... 我也尝试了这样的代码
dataGridView1.Columns[3].DefaultCellStyle.Format = "yyyyMMdd";
dataGridView1.Columns[5].DefaultCellStyle.Format = "yyyyMMdd";
dataGridView1.Columns[22].DefaultCellStyle.Format = "yyyyMMdd";
,但结果根本没有改变。 谁能给我一些建议?谢谢。
I am new to C# and I am working on a project.
I got a column that contained datetime from Excel, I am going to input the data into DataGridView via datatable.
What I have in my Excel, ex: 2022/05/29
I want to change to specific format like: 20220529
I think it should be really simple but I just cannot get it right.
What I have tried is like below:
int col = 0;
for (int i = 0; i <= 23; i++)
{
DataRow row = dt_d.NewRow();
dt_d.BeginLoadData();
for (int j = 2; j <= 21; j++)
{
if (excelRange.Cells[j, i].Value != null)
{
if (i == 3)
{
DateTime date1 = (DateTime)excelRange.Cells[j, 3];
date1.ToString("yyyyMMdd");
}
if (i == 5)
{
DateTime date2 = (DateTime)excelRange.Cells[j, 5];
date2.ToString("yyyyMMdd");
}
if (i == 22)
{
DateTime date3 = (DateTime)excelRange.Cells[j, 22];
date3.ToString("yyyyMMdd");
}
row[col] = excelRange.Cells[i, j].Value.ToString();
}
}
col++;
dt_d.EndLoadData();
dt_d.Rows.Add(row);
}
When I execute it, it give me a hresult: 0x800a03ec Exception...
I also tried code like these
dataGridView1.Columns[3].DefaultCellStyle.Format = "yyyyMMdd";
dataGridView1.Columns[5].DefaultCellStyle.Format = "yyyyMMdd";
dataGridView1.Columns[22].DefaultCellStyle.Format = "yyyyMMdd";
But the result doesn't change at all.
Can anyone give me some suggestion? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论