嘿,我正在尝试创建一个脚本,从excel中提取数据并将其插入SQL。
当我提取日期值并将其作为表的一部分时,问题就出现了。每当我尝试使用以下代码时,我都会在这篇文章的底部看到错误。提取并转换excel";相对日期";数字,是从设定日期开始计算的5位数。
代码:
for ($i = 0; $i -lt 6; $i++)
{
for ($i2 = 0;$i2 -lt 10; $i2++)
{
$ExcelDate = Import-Excel -Path $path -StartColumn 2 -EndColumn 2 -StartRow 7 -EndRow 20
-WorksheetName $WeekDays[$i]
[DateTime]::FromOADate($ExcelDate[$i2])
}
}
错误:
Cannot convert argument "d", with value: "@{Date Del.=44293}", for
"FromOADate" to type "System.Double": "Cannot convert the "@{Date Del.=44293}"
value of type "System.Management.Automation.PSCustomObject" to type
"System.Double"."
At H:My FilesJobsProjectsIn ProgressKillsheet Data ImportImporting data
test v1.ps1:75 char:9
+ [DateTime]::FromOADate($ExcelDate[$i2])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
我需要帮助将@{dateDel.=44293}更改为"日期";字符串值";的";44293〃;
Import-Excel cmdlet返回PSCustomObject类型的数组。单元格值存储为对象的属性,属性名称设置为列的标题名称。因此,要访问该值,您需要编写$ExcelDate[$i2].NameOfColumn
。
您应该注意,Import Excel通常能够将Date列转换为DateTime,因此不需要使用FromOADate
进行转换。
如果您不确定Powershell对象上有哪些可用属性,可以使用cmdlet Get-Member
进行检查。例如$ExcelDate[$i2] | Get-Member
For me输出:
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
MyExampleDateColumn NoteProperty datetime MyExampleDateColumn=2021-04-03 00:00:00