我正在尝试将CSV文件导入到新创建的Excel工作表中,但未能在此处(以及其他地方)使用现有的Q& A来解决此问题。
另外,我确信我这样做的方式比应该更难,所以如果你认为合适,请随意纠正这个臃肿的代码:
$varOneSheet = "OneSheet"
$xlsNewFile = New-Object -ComObject Excel.Application
$xlsNewFile.SheetsInNewWorkbook = 3
$xlsNewFile.displayAlerts = $false
$xlsNewFile.Visible = $false
$xlsWorkbook = $xlsNewFile.Workbooks.Add()
$sheetToRename = $xlsNewFile.Sheets.Item("Sheet1")
$sheetToRename.Name = $OneSheet
#this all works below, we need to push the data over to #xlsWorkbook now
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
$csvFilename = (".\DATA.CSV")
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$xlsCSVFile.Visible = $true
$tmpSheetTOFile = $xlsWorkbook.Sheets.Item(1)
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
#########################above is fine
#########################below should copy into $xlsWorkbook Sheet 1
$tmpWorksheet.Copy($tmpSheetTOFile)
上面的最后一行是失败点,产生:
Exception calling "Copy" with "1" argument(s): "Copy method of Worksheet class failed" At line:1 char:23 + $tmpWorksheet.Copy <<<< ($tmpSheetTOFile) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation
我真的需要创建一个单独的/临时的工作簿吗?为什么我无法在已保存的/现有工作簿上使用OpenText
?
答案 0 :(得分:1)
您正在创建两个不同的Excel应用程序实例:
$xlsNewFile = New-Object -ComObject Excel.Application
...
$xlsCSVFile = New-Object -ComObject Excel.Application
复制仅适用于同一实例,无论如何都不需要使用两个实例。只需删除
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
...
$xlsCSVFile.Visible = $true
并更改
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
...
$tmpWorksheet.Copy($tmpSheetTOFile)
到
$xlsNewFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$xlsNewFile.Workbooks.Item(2).Sheets.Item(1).Copy($tmpSheetTOFile)
话虽如此,Excel无论如何都会在导入CSV时自动创建一个带有新工作表的工作簿(这也是OpenText
不将CSV导入现有工作簿的原因),为什么呢?你需要首先将它复制到另一个新的工作簿?通常只需将导入的CSV保存为Excel工作簿就足够了。如果您需要额外的工作表,可以添加它们。
$wsName = 'OneSheet'
$csvFilename = '.\data.csv'
$xlsFilename = '.\data.xlsx'
$xl = New-Object -ComObject 'Excel.Application'
$xl.DisplayAlerts = $false
$xl.Visible = $false
$xl.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$wb = $xl.Workbooks.Item(1)
$ws = $wb.Sheets.Item(1)
$ws2 = $wb.Sheets.Add([Type]::Missing, $ws)
$ws3 = $wb.Sheets.Add([Type]::Missing, $ws2)
$ws.Name = $wsName
$wb.SaveAs($xlsFilename, 51)