先看看这里,学习一下
http://www.connectionstrings.com/?carrier=excel2007
含字段名的,要用HDR=Yes; 这时
注意Extended Properties="Excel 12.0;HDR=YES"中加了引号了,在c#中用\"表示引号
这样再运行就能正常取字段名了,刚才一直是乱码.
这样再运行就能正常取字段名了,刚才一直是乱码.
1 DataSet ds=new DataSet();
2 string strCon,strCmm;
3 strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+workdir+";Extended Properties=\"Excel 8.0;HDR=Yes;\""; //"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
4 strCmm="select top 1 * from [Sheet1$]";
5 OleDbConnection oleCnn=new OleDbConnection(strCon);
6 OleDbCommand oleCmm=new OleDbCommand(strCmm,oleCnn);
7 try
8 {
9 OleDbDataAdapter oleDa=new OleDbDataAdapter(oleCmm);
10 oleDa.Fill(ds,"test");
11 }
12 catch(System.Exception ex)
13 {
14 string error=ex.Message;
15 }
16 for(int i=0;i<ds.Tables[0].Columns.Count;i++)
17 {
18 listBox1.Items.Add(ds.Tables[0].Columns[i]);
19 }
2 string strCon,strCmm;
3 strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+workdir+";Extended Properties=\"Excel 8.0;HDR=Yes;\""; //"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
4 strCmm="select top 1 * from [Sheet1$]";
5 OleDbConnection oleCnn=new OleDbConnection(strCon);
6 OleDbCommand oleCmm=new OleDbCommand(strCmm,oleCnn);
7 try
8 {
9 OleDbDataAdapter oleDa=new OleDbDataAdapter(oleCmm);
10 oleDa.Fill(ds,"test");
11 }
12 catch(System.Exception ex)
13 {
14 string error=ex.Message;
15 }
16 for(int i=0;i<ds.Tables[0].Columns.Count;i++)
17 {
18 listBox1.Items.Add(ds.Tables[0].Columns[i]);
19 }