简体   繁体   English

从Excel工作表中读取数据

[英]Read data from excel sheet

I have an excel sheet(ms excel 2010) in my D drive named "test". 我的D驱动器中有一个名为“test”的excel表(ms excel 2010)。 I have data in it as follows 我的数据如下

 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 ............

How do I code in C# to read these URL one by one from the excel sheet and get the numerical value after "term=" ? 如何在C#中编码以从excel表中逐个读取这些URL并获取“term =”之后的数值?

Try this 尝试这个

        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();

Now your Excel sheet are in datatable, Which you can traverse to manipulate the string value in URL 现在您的Excel工作表位于数据表中,您可以遍历该工作表来操作URL中的字符串值

Edit 编辑

For getting String 获取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));
}

try this 尝试这个

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