读取Excel文件

[Flags]

private enum HDR { YES, NO };



/// <summary>

/// 读取Excel文件内容

/// </summary>

/// <param name="strFilePath">Excel文件路径</param>

/// <param name="HDR">YES(默认),表示第一行是标题,不做数据使用;NO,表示第一行不是标题,做数据使用</param>

/// <param name="EMEX">

/// EMEX(IMport EXport Mode)

/// IMEX=0 汇出模式 写入用途;1 汇入模式 读取用途;2 连結模式 读取写入用途

/// </param>

/// <returns>Excel内容</returns>

private DataSet GetExcel(string strFilePath, HDR hdr = HDR.YES, int EMEX = 0)

{

    DataSet ds = new DataSet();

    //Excel链接

    OleDbConnection objConn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0;HDR={0};IMEX={1};'", hdr, EMEX));

    objConn.Open();

    DataTable schemaTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    //获取Excel的表名,默认值是sheet1

    string tableName = schemaTable.Rows[0][2].ToString();



    string strSQL = "SELECT * FROM [" + tableName + "]";

    OleDbCommand objCmd = new OleDbCommand(strSQL, objConn);

    OleDbDataAdapter myData = new OleDbDataAdapter(strSQL, objConn);

    //填充数据

    myData.Fill(ds, tableName);



    objConn.Close();

    return ds;

}

 

你可能感兴趣的:(Excel)