我有一个由其他服务器更新的电子表格(在我的掌握),我需要自动将这些数据转化为SQL 2005中的数据始终是电子表格的第一页.但是,该工作表的名称会根据行数而变化.
有没有办法在不事先知道工作表名的情况下运行从Excel中提取数据的SSIS作业?它似乎依赖于工作表名称作为数据源,但我希望告诉它"工作表编号1"或类似的东西.
小智 7
我会将工作表名称编写为SSIS用户变量.如果您不反对将脚本任务插入SSIS包,请尝试:(基于链接文本)
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open("<Name of your excel app>.xls", 0, xlWorkBook true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Look up worksheet by index
Excel.Worksheet xlWorkSheet =(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
user::worksheetname = xlWorkSheet.Name;
/* Do clean up. Working with COM object */
Run Code Online (Sandbox Code Playgroud)
只是为了记录,我在脚本任务中使用此代码来解决问题。使用的变量是:Filename,SheetName。
请注意,我的 Excel 文件名是动态的。
// GET NAME OF FIRST SHEET
string filename = (string)Dts.Variables["Filename"].Value;
string sheetName = null;
string connStr =
String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"EXCEL 8.0;IMEX=1;\"", filename);
var conn = new OleDbConnection(connStr);
try
{
conn.Open();
using(var dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
var row0 = dtSheet.Rows[0];
sheetName = row0["TABLE_NAME"].ToString();
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
conn.Dispose();
}
if (!String.IsNullOrEmpty(sheetName))
{
Dts.Variables["SheetName"].Value = sheetName;
Dts.Events.FireInformation(1, "User::SheetName", sheetName, "", 0, ref dummy);
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
Dts.Events.FireError(0, "User::SheetName", "No SheetName found!", String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Run Code Online (Sandbox Code Playgroud)