处理动态excel表格

本文关键字:表格 excel 动态 处理 | 更新日期: 2023-09-27 17:53:27

我有一个情况下,我需要导入一个excel文件,有两个表到DB。我使用的是SSIS包。问题是,我可以通过设置表达式使excel工作表动态,但excel工作簿中的工作表也在更改名称。我怎样才能使表名更动态。我试过在我的DEV代码中使用Microsoft.Office.InterOp.excel,但是PROD没有安装excel。有人能帮我解决这个问题吗?

处理动态excel表格

尝试添加类似于下面脚本的内容,可以在SSIS Excel电子表格导入中的代码点-动态表名称中找到。它不需要在机器上安装Excel。

string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::ExcelFile"].Value.ToString();
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
}
Dts.Variables["User::SheetName"].Value = excelTables[0];
Dts.TaskResult = (int)ScriptResults.Success;

我使用SQL脚本来加载Excel文件,因为它是一个staging表,从那里它使用SSIS/T-SQL处理,它是相对快速和可靠的。你可以自己下载驱动程序,你不需要办公室安装使用这种方法。

/*Drop table if exists*/
IF OBJECT_ID(’table_1', 'U') IS NOT NULL
EXEC ('DROP TABLE table_1')
/*Load using access driver, can probably work with excel too.*/
select *
into [table_1]
from openrowset('MSDASQL'
               ,'Driver={Microsoft Access Text Driver (*.txt, *.csv)}'
               ,'select * from 'D:'folder'file.csv' ')