下面是将读取Excel中数据的方法,其中一些注意事项如下:
用OLEDB进行Excel文件数据的读取,并返回DataSet数据集。其中有几点需要注意的:
1.连接字符串中参数IMEX 的值:
0 is Export mode 1 is Import mode 2 is Linked mode (full update capabilities)
IMEX有3个值:当IMEX=2 时,EXCEL文档中同时含有字符型和数字型时,比如第C列有3个值,2个为数值型 123,1个为字符型 ABC,当导入时,
页面不报错了,但库里只显示数值型的123,而字符型的ABC则呈现为空值。当IMEX=1时,无上述情况发生,库里可正确呈现 123 和 ABC.
2.参数HDR的值:
HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
3.参数Excel 8.0
对于Excel 97以上版本都用Excel 8.0
1/// <summary>
2/// 读取Excel文件,将内容存储在DataSet中
3/// </summary>
4/// <param name="opnFileName">带路径的Excel文件名</param>
5/// <returns>DataSet</returns>
6private DataSet ExcelToDataSet(string opnFileName)
7{
8string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+opnFileName+";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
9OleDbConnection conn = new OleDbConnection(strConn);
10string strExcel = "";
11OleDbDataAdapter myCommand = null;
12DataSet ds = new DataSet();
13strExcel = "select * from [sheet1$]";
14try
15{
16conn.Open();
17myCommand = new OleDbDataAdapter(strExcel, strConn);
18myCommand.Fill(ds,"dtSource");
19return ds;
20}
21catch (Exception ex)
22{
23MessageBox.Show("导入出错:" + ex, "错误信息");
24return ds;
25}
26finally
27{
28conn.Close();
29conn.Dispose();
30}
31}
32