[英]Reading last row of specific column in Excel sheet and appending more data - in PowerShell
I'm trying to write data to specific column in an Excel spreadsheet with PowerShell.我正在尝试使用 PowerShell 将数据写入 Excel 电子表格中的特定列。 I would like to start below last row with data and continiue downwards.
我想从最后一行的数据开始,然后继续向下。 On machine I don't have Excel installed so COM won't work for me.
在机器上我没有安装 Excel 所以 COM 对我不起作用。 I'm currently using
Import-Excel
to read whole sheet and used Open-ExcelPackage
to read specific cell values.我目前正在使用
Import-Excel
来读取整个工作表,并使用Open-ExcelPackage
来读取特定的单元格值。
I could do this in CSV
file as opposed to .xlsx
if it's easier.如果更容易,我可以在
CSV
文件中执行此操作,而不是.xlsx
。
Any help would be great!任何帮助都会很棒!
Download PSExcel module from https://github.com/RamblingCookieMonster/PSExcel Import it using Import-Module.从https://github.com/RamblingCookieMonster/PSExcel下载 PSExcel 模块 使用 Import-Module 导入。
Then use the following code:然后使用以下代码:
$File = "Path to xlxs file"
$WSName = "SheetName"
$Excel = New-Excel -Path $File
$Worksheet = $Excel | Get-WorkSheet -Name $WSName
$SampleRows = @()
$SampleRows += [PSCustomObject]@{"A" = 1; "B" = 2; "C" = 3; "F" = 4 }
$row_to_insert = $SampleRows.count
$Worksheet.InsertRow($Worksheet.Dimension.Rows,$row_to_insert)
$WorkSheet.Cells["$($Worksheet.Dimension.Start.Address -replace ""\d"")$($Worksheet.Dimension.End.Row):$($Worksheet.Dimension.End.Address)"].Copy($WorkSheet.Cells["$($Worksheet.Dimension.Start.Address -replace ""\d"")$($Worksheet.Dimension.End.Row - $row_to_insert):$($Worksheet.Dimension.End.Address -replace ""\d"")$($Worksheet.Dimension.End.Row - $row_to_insert)"]);
$WorkSheet.Cells["$($Worksheet.Dimension.Start.Address -replace ""\d"")$($Worksheet.Dimension.End.Row):$($Worksheet.Dimension.End.Address)"] | % {$_.Value = ""}
ForEach ($Row in $SampleRows) {
ForEach ($data in $Row.PSObject.Properties.Name) {
$WorkSheet.Cells["$data$($Worksheet.Dimension.Rows)"].Value = $SampleRow.$data
}
}
$Excel | Close-Excel -Save
This code adds 1 row after the last row in the selected worksheet and adds values to this row from $SampleRows .... I think you got the idea.此代码在所选工作表的最后一行之后添加 1 行,并从$SampleRows向该行添加值 .... 我想你明白了。 if you need add more rows to $SampleRows array.
如果您需要向$SampleRows数组添加更多行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.