簡體   English   中英

從Excel工作表中讀取數據

[英]Read data from excel sheet

我的D驅動器中有一個名為“test”的excel表(ms excel 2010)。 我的數據如下

 Id                URL  
 1          http://www.sample.com/term=100898731%5Buid%5D&cmd=DetailsSearch&report=xml&format=text              
 2          http://www.sample.com/term==101120693%5Buid%5D&cmd=DetailsSearch&report=xml&format=text             
 3          http://www.sample.com/term==100893225%5Buid%5D&cmd=DetailsSearch&report=xml&format=text     
...........continues ............

如何在C#中編碼以從excel表中逐個讀取這些URL並獲取“term =”之后的數值?

嘗試這個

        System.Data.OleDb.OleDbConnection mCon;  
        mCon = new System.Data.OleDb.OleDbConnection();
        mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + pathOfFile + ";Extended Properties=\"Excel 12.0;HDR=YES\";");
        System.Data.OleDb.OleDbCommand Command = new System.Data.OleDb.OleDbCommand();
        DataTable DTable = new DataTable();            
        string strSelectQuery, mstrDBTable;
        System.Data.OleDb.OleDbDataAdapter DataAdapter = new System.Data.OleDb.OleDbDataAdapter();            

        strSelectQuery = "SELECT * FROM [" + YourSheetName + "]"; 
      // YourSheetName is the sheet in xls from where you want to load data e.g Sheet1$
        if (mCon.State == ConnectionState.Closed)
        {
            mCon.Open();
        }
        DataAdapter = new System.Data.OleDb.OleDbDataAdapter(strSelectQuery, mCon);
        DataAdapter.Fill(DTable );
        mCon.Close();

現在您的Excel工作表位於數據表中,您可以遍歷該工作表來操作URL中的字符串值

編輯

獲取String

for(int i = 0; i<Dtable.Rows.Count;i++)
{
    string str = Dtable.Rows[i][1].ToString();
    string YourNumber = str.Substring((str.IndexOf('=') + 1), (str.IndexOf('%') - str.IndexOf('=')-1));
}

嘗試這個

string fileName = "Activity.xls";
                            savePath += fileName; 
OleDbConnection conn= new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(savePath) + ";Extended Properties='Excel 12.0;HDR=YES'");
    if (conn.State == ConnectionState.Closed)
    conn.Open();
    string query = "select * from [Sheet1$]";
      OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
                                DataSet ds = new DataSet();
                                da.Fill(ds, "Activities");
                                dt = ds.Tables[0];
                                conn.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM