【发布时间】:2017-02-11 10:08:25
【问题描述】:
我尝试将一个带有条件的 Excel 导入我的 DataTable。 示例: - 用户有我提供的 excel 导入模板,第一行 0 作为列标题(ItemCode、QTY、SerialNo、Remarks)。但是由于用户可能会不小心在我准备好的列的任何地方插入一些不需要的列名,或者删除我的列名之一。
无论发生什么,我都会尝试构建代码,系统只检测到我的标准就绪列标题(ItemCode、QTY、SerialNo、Remarks)。并且只会在excel中添加列而忽略那些不小心删除的列名。
在允许将那些特定列导入dataTable之前,对列名检测进行编码的最佳方法是什么?
下面是我当前的excel导入代码(我尝试添加上面的条件代码)
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;
}
我尝试用谷歌搜索,发现很多提示,但仍然无法使其工作。 谢谢你的建议。
【问题讨论】: