您的位置:首页 > 其它

.Net 读取Excel文章内容

2008-09-26 14:52 267 查看
 
不多说了,直接上代码,呵呵

两个函数,第一个为获取Excel文档路径,第二个读取并以DataSet类型返回该Excel中Sheet1内容

 

 获取Excel文档路径




Code
 1



/**//// <summary>
 2

/// 获取Excel文档路径
 3

/// </summary>
 4

/// <returns></returns>
 5

public string GetFilePath()
 6





{
 7

    OpenFileDialog ofd = new OpenFileDialog();
 8

    ofd.Title = "打开Excel文件";
 9

    ofd.FileName = "";
10

    ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
11

    ofd.Filter = "Execl文件(*.xls)|*.xls|All files (*.*)|*.*"; 
12

    ofd.ValidateNames = true;     //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
13

    ofd.CheckFileExists = true; //验证路径有效性
14

    ofd.CheckPathExists = true; //验证文件有效性
15

    try
16



    

{
17

        if (ofd.ShowDialog() == DialogResult.OK)
18



        

{
19

            return ofd.FileName;
20

        }
21

        else
22



        

{
23

            return "文件载入出错,请重新选择";
24

        }
25

    }
26

    catch (Exception ex)
27



    

{
28

        MessageBox.Show(ex.Message.ToString());
29

        return "文件载入出错,请重新选择";
30

    }
31

}
 

读取并返回Sheet1中的数据




Code
 1



/**//// <summary>
 2

/// 读取并返回Sheet1中的数据
 3

/// </summary>
 4

/// <param name="opnFileName"></param>
 5

/// <returns></returns>
 6

private DataSet ExcelToDataSet(string opnFileName)
 7





{
 8

    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+opnFileName+";Extended Properties=/"Excel 8.0;HDR=YES;IMEX=1/"";
 9

    OleDbConnection conn = new OleDbConnection(strConn);            
10

    string strExcel = "";
11

    OleDbDataAdapter myCommand = null;
12

    DataSet ds = new DataSet();
13

    strExcel = "select * from [sheet1$]";
14

    try
15





{
16

        conn.Open();
17

        myCommand = new OleDbDataAdapter(strExcel, strConn);
18

        myCommand.Fill(ds,"dtSource");
19

        return ds;
20

    }
21

    catch (Exception ex)
22



    

{
23

        MessageBox.Show("导入出错:" + ex, "错误信息");
24

        return ds;
25

    }
26

    finally
27



    

{
28

        conn.Close();
29

        conn.Dispose();
30

    }
31

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息