更改C#中数据表中列的数据类型 [英] Change datatype of a column in a datatable in C#
本文介绍了更改C#中数据表中列的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HI专家,我有一个数据表,我正在读取excel文件中的值,其采用的数据类型是字符串。我有一个DateTime格式的第4列。但它的读数为字符串。如何将String转换为DateTime格式。我只有一列来更改数据类型。请帮帮忙?
我尝试过:
HI Experts, I have a Data table where i am reading the values from a excel file, The datatype its taking is string. I have a column 4 with DateTime format. But its reading as string. How do i convert String to DateTime format. I just have one column to change the Datatype. Please help?
What I have tried:
DataTable dtCloned = dt.Clone();
dtCloned.Columns[4].DataType = typeof(DateTime);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
推荐答案
如果 DataTable $ c,则无法更改列数据类型$ c>中有数据。
您可以尝试确保在阅读之前将列设置为excel中的日期/时间。
我写了一篇文章,其中包含允许您导入xlsx或csv文件的代码,如果您需要/需要,您可以手动指定每列的数据类型,或者让代码自己动手。
CSV / Excel文件解析器 - 重访 [ ^ ]
You can't change the column datatype if aDataTable
has data in it.
You can try making sure the column is set to be a date/time in excel before reading it.
I wrote an article that includes code which allows you to import xlsx or csv files, and if you want/need to, you can manually specify the datatype for each column, or let the code finger it out on its own.
CSV/Excel File Parser - A Revisit[^]
这篇关于更改C#中数据表中列的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文