简体   繁体   中英

C# Excel input concatenate two columns

I have been struggling to find an answer to this. I am importing an Excel spreadsheet into C# using Oledb. This works fine, however while importing I wish to join two of the Excel columns together ie concatenate them.

This is the code I currently have:

string PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + textBox1.Text + ";Extended Properties=\"Excel 12.0 XML;HDR=Yes;\";";
        OleDbConnection conn = new OleDbConnection(PathConn);
        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select [ID], [Subject], [Catalog], [Last], [First Name], [Descr], [Mark] from[" + textBox2.Text + "$]", conn);
        DataTable dt = new DataTable();
        myDataAdapter.Fill(dt);
        dataGridView1.DataSource = dt;

The code above is working fine. The two columns I wish to join are Subject and Catalog and for this to be called Module. Subject is a string of three letters and Catalog four numbers. Is there a way to do this within the select statement or an alternative method?

Many thanks in advance.

You can "CONCAT" in the query:

https://msdn.microsoft.com/es-es/library/hh231515(v=sql.120).aspx

OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select [ID], CONCAT( [Subject], [Catalog] ) AS subject_catalog, [Last], [First Name], [Descr], [Mark] from[" + textBox2.Text + "$]", conn);

Change your OleDbAdapter query like this:

OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select [ID], [Subject] + ' ' + [Catalog] AS [Module], [Last], [First Name], [Descr], [Mark] from[" + textBox2.Text + "$]", conn);

Notice that [Subject] + ' ' + [Catalog] AS [Module] are combined into a single string and placed under Module alias.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM