我正在使用 SSIS,我需要使用 SSIS 将具有以下 (Yellos) 格式的多个文件加载到 SQL
如您所见,问题在于文件的格式很糟糕,仅在填充 A 列时才处理/使用记录(例如:忽略行# 14 - X ),并且我需要将 D1 中的值插入到日期中专栏。
有什么建议吗?
问候!
最佳答案
让我们把这个问题分成 3 个子问题:
- 从
D1
获取日期值 - 从第 4 行开始读取
- 忽略 Column1 为 NULL 的所有行
解决方案
1。获取D1的日期值
- 创建 2 个 SSIS 变量
@[User::FilePath]
(字符串类型),其中包含 Excel 文件路径@[User::FileDate ]
(字符串类型)我们将使用它来存储日期值 - 添加脚本任务,选择脚本语言为Visual Basic
- 选择
@[User::FilePath]
作为只读变量,并选择@[User::FileDate]
作为读写变量变量 - 打开脚本编辑器并使用以下代码检索日期值并将其存储到
@[User::FileDate]
这将搜索名为 Refunds
的工作表,并从中提取日期值并将该值存储到 @[User::FileDate]
m_strExcelPath = Dts.Variables.Item("FilePath").Value.ToString
Dim strSheetname As String = String.Empty
Dim strDate as String = String.Empty
m_strExcelConnectionString = Me.BuildConnectionString()
Try
Using OleDBCon As New OleDbConnection(m_strExcelConnectionString)
If OleDBCon.State <> ConnectionState.Open Then
OleDBCon.Open()
End If
'Get all WorkSheets
m_dtschemaTable = OleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'Loop over work sheet to get the first one (the excel may contains temporary sheets or deleted ones
For Each schRow As DataRow In m_dtschemaTable.Rows
strSheetname = schRow("TABLE_NAME").ToString
If Not strSheetname.EndsWith("_") AndAlso strSheetname.EndsWith("$") Then
If Not strSheetname.Tolower.Contains("refunds") Then Continue For
Using cmd As New OleDbCommand("SELECT * FROM [" & strSheetname & "A1:D1]", OleDBCon)
Dim dtTable As New DataTable("Table1")
cmd.CommandType = CommandType.Text
Using daGetDataFromSheet As New OleDbDataAdapter(cmd)
daGetDataFromSheet.Fill(dtTable)
'Get Value from column 4 (3 because it is a zero-based index
strDate = dtTable.Rows(0).Item(3).ToString
End Using
End Using
'when the first correct sheet is found there is no need to check others
Exit For
End If
Next
OleDBCon.Close()
End Using
Catch ex As Exception
Throw New Exception(ex.Message, ex)
End Tr
Dts.Variables.Item("FileDate").Value = strDate
Dts.TaskResult = ScriptResults.Success
End Sub
在 DataFlow 任务中添加
派生列转换
,使用以下表达式添加派生列@[User::FileDate]
2。从第 4 行开始读取
我们假设 Excel 文件路径存储在 @[User::FilePath]
- 首先打开
Excel 连接管理器
并取消选中第一行有列名称
复选框 - 在“数据流任务”中,双击 Excel 源
- 将源设置为
SQL 命令
- 使用以下命令:
SELECT * FROM [Refunds$A4:D]
,因此将从第 4 行开始读取 - 列名称将如下 F1 ... F4 ,在 Excel 源中,您可以转到“列”选项卡并为列名称指定别名,因此在数据流任务中将显示它们及其别名<
3。忽略 Column1 为 NULL 的所有行
- 在 Excel 源之后添加条件拆分
根据以下表达式分割流
ISNULL([F1]) == False
如果您没有为 F1
提供别名,否则使用别名
最后,请记住,您必须添加一个包含日期值的派生列(正如我们在第一个子问题中所述)
关于sql-server - 将多个数据从excel加载到sql SSIS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47517548/