我有一个Excel文件,如果用户点击一个按钮,想要在数据网格视图中显示excel文件。列是
Date, Day, Start time, End time, Totaltime, Difftime and Work done.
我的样本行数据如下是A10行和A11行。
A10 01-03-2014 Saturda 8:20 22:30 13:40 4:40设计
A11 02-03-2014 Sunday 9:00 21:00 11:30 2:30 Coding
我的行位于10到40之间,列来自A-G
如果我将其导入数据网格视图日期和时间未正确显示。 01/03/2014显示为404977.我希望代码将Excel文件导出到datagridview,并且datagridview应显示与Excel相同的内容。任何人都可以解释如何在C#中使用dateg,start,end,total,diff,以datagridview列完成工作吗?
答案 0 :(得分:0)
我假设您要导入窗口形成datagridview,
Excel 2003,
private void button1_Click(object sender, EventArgs e)
{
String name = "Yoursheetname";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
for Excel 2007,
private void button1_Click(object sender, EventArgs e)
{
String name = "Yoursheetname";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}