简体   繁体   中英

C# How to import specific column name of excel into DataTable

I try to import an excel in to my DataTable with condition. example : - The user have my provided excel import template, with the first row 0 as the column header (ItemCode, QTY, SerialNo, Remarks). But due to the user might accidentally insert few unwanted column name in anywhere of my per-ready column or delete one of my column name.

I try to build a code regardless what happen, the system only detect my standard ready column header (ItemCode, QTY, SerialNo, Remarks). And only will add the column still within the excel and ignore those accidentally delete column name.

What is the best way to code the detection of the column name when is exist before allow to import those specific column into dataTable?

Below is my current excel import code (which i try to add the above condition code)

    private DataTable ReadExcelToDataTable(string filePath)
    {
        tableSalesOrder = new DataTable("dtSO");
        string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"", filePath);
        using (OleDbConnection dbConnection = new OleDbConnection(strConn))
        {
            dbConnection.Open();
            DataTable dtExcelSchema = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sSheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

            dbConnection.Close();

            using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT DISTINCT * FROM [" + sSheetName + "]", dbConnection)) //rename sheet if required!
                dbAdapter.Fill(tableSalesOrder);
        }
        return tableSalesOrder;
    }   

I have try to google around, found many hint but still unable to make it work. Thank you for any advice.

If you just wanted to ignore extra columns, you could use

 ... new OleDbDataAdapter("Select Distinct ItemCode, QTY, SerialNo, Remarks FROM [" + sSheetName + "] ...

If you need to cope with some of these columns being missing, then it is slightly more complicated. You need to get a list of columns in the excel sheet , eg

DataTable dt = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, 
                new object[] { null,null, sSheetName, null });

List<string> columnNames = new List<string>();
foreach (DataRow row in dt.Rows)
    columnNames.Add(row["Column_name"].ToString()); 

Then you need to build up your select statement to only include the columns that you want and that exist in the excel sheet.

You could set up your workbooks with named ranges, and extract those . That way it'll work even if they accidentally change the name or insert extra columns. You can select the named range with something like this:

var sql = "SELECT * FROM [Workbook$MyNamedRange]"
using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter(sql, dbConnection));
dbAdapter.Fill(tableSalesOrder);

I solve the issue by using different method, I got the idea from both your guys advise. In fact, after i do some test on my origin code which posted, it only will import according the column name which i define which is ItemCode, Qty, SerialNo & Remakrs at my gridView which my dataTable have assign to it as data source.

The only issue is when one of the column deleted, my import process will be facing problem. This due to the datatable never assign any column name after it created. I solve it by improve the dataTable set and redefine the column name into It.

        if (tableSalesOrder == null)
        {
            tableSalesOrder = new DataTable("dtSO");
            DataColumn colItemCode = new DataColumn("ItemCode",typeof(string));
            ......

            tableSalesOrder.Columns.Add(colItemCode);
            ......
        }
        else
        {
            tableSalesOrder.Clear();
        }

Thanks guys for the help. Finally I found where the bugs were.

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