我会尽力解释我最容易理解的担忧:
我正在创建一个 SSIS 包,从 Excel 源导入数据并将其加载到 SQL 表。
我可以毫无问题地使用工作表名称检索数据,但是这个包正在循环遍历多个具有不同工作表名称、工作表位置的 Excel 文件(对于文件 X,工作表索引为 0,对于文件 Y 工作表索引为 4 等等),所以我需要获取数据表名称(所有Excel文件的名称相同,但维度不同。)
我已经设置了一个 Srcipt 任务,使用以下代码获取存储在该 excel 文件中的所有表:
string excelFile;
string connectionString;
OleDbConnection excelConnection;
DataTable tablesInFile;
string currentTable;
int tableIndex = 0;
string[] excelTables = new string[5];
excelFile = Dts.Variables["FileName"].Value.ToString();
connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.16.0;Data Source={0};Extended Properties=\"EXCEL 12.0 XML;HDR=YES;\"", excelFile);
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
foreach (DataRow tableInFile in tablesInFile.Rows)
{
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
Dts.Variables["ExcelTables"].Value = excelTables;
但是这是我执行后得到的结果:仅存储了“Sheet1$”值,并且我的数据表中没有任何消息:(
请帮我解决这个话题
对于有一天遇到同样问题的人,以下是我如何从数据表中获取数据:
首先,我在数据流任务内部创建了脚本组件,并通过创建与数据表中“输入和输出”部分下的列一样多的输出列来设置脚本组件 (不要忘记在窗口右侧的数据类型属性中设置列的数据类型)
然后我创建了脚本:
首先添加Excel COM引用: -> 单击脚本组件中的编辑脚本按钮 -> 在屏幕右侧,右键单击“引用”和“添加引用...” -> 在 COM 库中,搜索“Microsoft Excel 16.0 Object Library”并选中该框,然后单击“确定”。
您需要通过在代码开头的命名空间部分添加此行来使用此对象库:
使用 Excel = Microsoft.Office.Interop.Excel;
公共重写 void CreateNewOutputRows() { // Var ExcelFilePath = Excel 文件的路径 字符串 excelFilePath = Variables.FilePath;
// Create new excel instance Excel.Application excelApp = new Excel.Application(); // Open Excel file Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(excelFilePath); // Set table to empty for the moment Excel.ListObject table = null; // For each sheet in excel file... foreach (Excel.Worksheet sheet in excelWorkbook.Sheets) { // For each object in the sheet... foreach (Excel.ListObject tbl in sheet.ListObjects) { // If object name is equal to the table name provided if (tbl.Name == "MyTable") { // Var table = table name table = tbl; break; } } // If table has been found then we get out the loop, else we search in another sheet if (table != null) { break; } } // If the table is not empty if (table != null) { // Get the number of rows in the table int rowCount = table.ListRows.Count; // For each row in the table... foreach (Excel.ListRow row in table.ListRows) { // Add new row Output0Buffer.AddRow(); // Insert in output table (Column1..ColumnX) --> value of table from excel sheet 1..X Output0Buffer.Column1 = Convert.ToString(row.Range[1, 1].Value2); Output0Buffer.Column2 = Convert.ToString(row.Range[1, 2].Value2); Output0Buffer.Column3 = Convert.ToString(row.Range[1, 3].Value2); } } // Close excel file excelWorkbook.Close(0); // Quit excel application excelApp.Quit();
}
重要: