将Excel文件导入SQL Server数据库时出错

时间:2017-05-30 09:02:18

标签: sql-server powershell import

我想将Excel文件导入我的SQL Server DB。以下是我的代码:

$dir = "\\server\files\"
$latest = Get-ChildItem -Path $dir |
          Where-Object {$_.name -like "*Data Action source *"} |
          Sort-Object LastWriteTime -Descending |
          Select-Object -First 1
Write-Output "The latest file is: $latest"
Write-SqlTableData -ServerInstance "instance1" -DatabaseName "db1" -SchemaName dbo -TableName Table1 -InputData $latest -Force
Write-Output "The latest file is $latest. Let's start the import"

代码很好地选择了最新的文件但是当它插入到数据库中时它失败并出现以下错误:

  

Write-SqlTableData:找不到.Net类型'System.IO.DirectoryInfo'与列'Directory'的SQL类型之间的映射。考虑删除该类型的列并重复操作

1 个答案:

答案 0 :(得分:0)

错误:变量$latest属于System.IO.DirectoryInfo类型,Write-SqlTableData命令的-InputData参数不期望这样。

在控制台中运行此行以获取文档:

Get-Help Write-SqlTableData -Full

在那里,您会看到-InputData

的此条目
-InputData <PSObject>
    Specifies the data to write to the database.

    Typical input data is a System.Data.DataTable, but you can specify System.Data.DataSet or
    System.Data.DateRow objects.

    Required?                    true
    Position?                    named
    Default value                none
    Accept pipeline input?       true (ByValue)
    Accept wildcard characters?  false

因此,解决方案是将csv转换为此命令可以理解的格式。第一步是实际将数据导入PowerShell,因为您拥有的只是文件信息(路径,大小等)

下面,我将CSV转换为psobject数据类型。这可能仍然会给您一个错误。要转换为可接受的System.Data.Datablecheck out this link

dir = "\\server\files\"
$latest = Get-ChildItem -Path $dir |
          Where-Object {$_.name -like "*Data Action source *"} |
          Sort-Object LastWriteTime -Descending |
          Select-Object -First 1
Write-Output "The latest file is: $latest"

# Import CSV to get the data
$csvData = Import-csv $latest.FullName

# Convert to psobject. This may still be rejected; I can't test. If it is, convert to DataTable.
$thingToImport = [psobject]$csvData

Write-SqlTableData -ServerInstance "instance1" -DatabaseName "db1" -SchemaName dbo -TableName Table1 -InputData $thingToImport -Force
Write-Output "The latest file is $latest. Let's start the import"