从excel问题中读取日期字段 [英] Reading date field from excel problem
问题描述
我正在尝试使用此代码阅读excel文件。
< pre lang =c#> 使用(OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// 获取Excel文件中的所有表格
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null );
// 遍历所有表格以获取数据
< span class =code-keyword> foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr [ TABLE_NAME]。ToString() ;
if (!sheetName.EndsWith( $))
继续;
// 获取工作表中的所有行
cmd。 CommandText = SELECT * FROM [ + sheetName + ];
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
ds.Tables.Add(dt);
}
cmd = null ;
conn.Close();
}
但问题是,在读取是否有任何日期字段时,它会转换为double值。我该如何处理...
请帮助
))
继续;
// 获取工作表中的所有行
cmd.CommandText = SELECT * FROM [ + sheetName + ];
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
ds.Tables.Add(dt);
}
cmd = null ;
conn.Close();
}
但问题是,在读取是否有任何日期字段时,它会转换为double值。我该如何处理...
请帮助
日期作为双打存储在Excel中,并显示为日期为根据Excel工作表上的格式。您需要明确地转换它。
对于Date列中的每个单元格,请执行以下操作:
DateTime conv = DateTime.FromOADate( d); // 其中d是提取的日期值
希望有所帮助。
Hi,
I am trying to read an excel file using this code.
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
if (!sheetName.EndsWith("$"))
continue;
// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
But the problem is that while reading if there is any date field, it gets converted to a double value. How can i handle that...
Pls help
")) continue; // Get all rows from the Sheet cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; DataTable dt = new DataTable(); dt.TableName = sheetName; OleDbDataAdapter da = new OleDbDataAdapter(cmd); da.Fill(dt); ds.Tables.Add(dt); } cmd = null; conn.Close(); }
But the problem is that while reading if there is any date field, it gets converted to a double value. How can i handle that...
Pls help
Dates are stored in Excel as doubles, and displayed as dates as per the formatting on the excel sheet. You would need to convert this explicitly.
For each cell in the Date column, do this:
DateTime conv = DateTime.FromOADate(d); // where d is the date value fetched
Hope that helps.
这篇关于从excel问题中读取日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!