我有一个SSIS数据导入包,它使用源Excel电子表格,然后将数据导入SQL Server数据库表。我没有成功自动化此过程,因为Excel文件的工作表名称每天都在更改。因此,我必须在每天运行导入之前手动更改工作表名称。作为警告,永远不会有任何其他工作表。
我可以为工作表名称创建变量吗? 我可以使用通配符而不是工作表名称吗? 在启动导入作业之前,我是否最好创建一个Excel宏或类似的更改工作表名称?
答案 0 :(得分:1)
我使用跟随脚本任务(C#):
System.Data.OleDb.OleDbConnection objConn;
DataTable dt;
string connStr = ""; //Use the same connection string that you have in your package
objConn = new System.Data.OleDb.OleDbConnection(ConnStr);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbShemaGuid.Tables,null);
objConn.Close();
foreach(DataRow r in dt.Rows)
{
//for some reason there is always a duplicate sheet with underscore.
string t = r["TABLE_NAME"].ToString();
//Note if more than one sheet exist this will only capture the last one
if(t.Substring(t.Length-1)!="_")
{
Dts.Variables["YourVariable"].Value = t;
}
}
然后在SSIS中,我添加了另一个变量来构建我的SQL。
新变量"从["中选择* +"你的变量" +"]"
最后在Excel Source中将数据源设置为该SQL变量。
答案 1 :(得分:1)
如果对您或其他人有帮助,在相同的情况下,这对我非常有用:
必需的包级字符串变量2:
varDirectoryList-您将在SSIS内部将其用于每个循环变量映射
varWorkSheet-这将保存您更改的工作表名称。由于您只有1,所以非常完美。
设置:
在您的Scrip任务中添加以下代码:
using System.Data.OleDb;
public void Main()
{
// store file name passed into Script Task
string WorkbookFileName = Dts.Variables["User::varDirectoryList"].Value.ToString();
// setup connection string
string connStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"EXCEL 12.0;HDR=Yes;IMEX=1;\"", WorkbookFileName);
// setup connection to Workbook
using (var conn = new OleDbConnection(connStr))
{
try
{
// connect to Workbook
conn.Open();
// get Workbook schema
using (DataTable worksheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
// in ReadWrite variable passed into Script Task, store third column in the first
// row of the DataTable which contains the name of the first Worksheet
Dts.Variables["User::varWorkSheet"].Value = worksheets.Rows[0][2].ToString();
//Uncomment to view first worksheet name of excel file. For testing purposes.
MessageBox.Show(Dts.Variables["User::varWorkSheet"].Value.ToString());
}
}
catch (Exception)
{
throw;
}
}
}
设置并运行后,将出现一个消息框,显示每个工作簿的工作表名称更改。
只要列结构保持不变,就应该照顾好它。
如果您碰巧获得的文件在一列中具有多种数据类型;您可以在连接字符串中使用IMEX = 1,从而在导入时将数据类型强制为DT_WSTR。
希望这会有所帮助:-)
答案 2 :(得分:0)
如果您使用SSIS导入工作表,则可以使用脚本任务查找工作表的名称,然后更改名称或您需要执行的任何其他操作,以使其适合导入的其余部分。以下是查找我找到的工作表here
的示例Dim excel As New Microsoft.Office.Interop. Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop. Excel.Workbook
Dim wSheet As Microsoft.Office.Interop. Excel.Worksheet
wBook = excel.Workbooks.Open
wSheet = wBook.ActiveSheet()
For Each wSheet In wBook.Sheets
MsgBox(wSheet.Name)
Next
在MsgBox行上,您可以更改名称或将其报告给另一个进程