[英]How to create a new sheet in excel with powershell script
我的问题在标题中,我不知道如何使用 powershell 脚本在 excel 中创建新工作表。
这是我的代码:
#Define locations and delimiter
$csv = $pathcsv
$xlsx = $pathxlsx
$delimiter = "," #Specify the delimiter used in the file
# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
# Execute & delete the import query
$query.Refresh()
$query.Delete()
# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$Workbook = $excel.Workbooks.Open($pathxlsx)
Add-Worksheet -ExcelPackage $excel -WorkSheetname "test"
$excel.Quit()
pause
所以我尝试命令 Add-Worksheet -ExcelPackage $excel -WorkSheetname "test" 但它似乎不起作用,你能帮我吗?
我收到以下错误:
添加工作表:无法处理参数“ExcelPackage”上的参数转换。 无法将值“Microsoft.Office.Interop.Excel.ApplicationClass”转换为类型“Microsoft.Office.Interop.Excel.ApplicationClass”和类型“OfficeOpenXml.ExcelPackage”。 Au caractère C:....\\NEW.ps1:125 : 29
~~~~~~
谢谢
要将新工作表作为最后一个工作表附加到打开的 Excel 文件中,您可以执行以下操作:
删除行Add-Worksheet -ExcelPackage $excel -WorkSheetname "test"
并改为写入:
# get the last sheet in the workbook
$lastSheet = $Workbook.WorkSheets($Workbook.WorkSheets.Count)
# create a new sheet and insert it before the last sheet
$newSheet = $workbook.WorkSheets.Add($lastSheet)
# give it a name
$newSheet.Name = 'test'
# now move the previous last sheet before the new sheet, so now THAT will become the last
$lastSheet.Move($newSheet)
# Save & close the Workbook as XLSX.
$workbook.SaveAs("D:\Test\test.xlsx",51)
$excel.Quit()
# don't forget to clear the COM objects from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($lastSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($newSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.