如何通过PowerShell调整Excel工作表中特定单元格的大小?
调整Excel特定单元格大小的PowerShell实现
核心说明
Excel中单元格的大小由其所在列的宽度和行的高度决定,因此调整特定单元格的大小,本质是调整该单元格对应的列宽或行高,也可以让Excel自动适配内容大小。
具体实现代码
以下是针对你的脚本,添加调整单元格大小的几种常用方式:
1. 手动指定列宽/行高
如果需要固定某列或某行的大小,直接设置对应的ColumnWidth(单位:字符)和RowHeight(单位:磅)即可:
# 调整第1列(A列)的宽度为25字符 $SelectedSourceList.Columns.Item(1).ColumnWidth = 25 # 调整第1行的高度为22磅 $SelectedSourceList.Rows.Item(1).RowHeight = 22 # 调整第6列(F列)的宽度为30字符(对应你脚本中写入的C27单元格) $SelectedSourceList.Columns.Item(6).ColumnWidth = 30 # 调整第27行的高度为20磅 $SelectedSourceList.Rows.Item(27).RowHeight = 20
2. 自动适配内容大小
让Excel根据单元格内的内容自动调整列宽或行高,使用AutoFit()方法:
# 让第2列(B列)自动适配内容宽度 $SelectedSourceList.Columns.Item(2).AutoFit() # 让第3列(C列)自动适配内容宽度 $SelectedSourceList.Columns.Item(3).AutoFit() # 如果需要批量调整多列,比如A到F列 $SelectedSourceList.Range("A:F").Columns.AutoFit()
3. 调整特定单元格范围的大小
如果需要调整某一片单元格区域的列宽和行高,可以先选中范围再设置:
# 选中A1到C3的单元格范围 $targetRange = $SelectedSourceList.Range("A1:C3") # 设置该范围内所有列的宽度为20字符 $targetRange.Columns.ColumnWidth = 20 # 设置该范围内所有行的高度为18磅 $targetRange.Rows.RowHeight = 18
整合到你的脚本中
将上述代码添加到你写入单元格内容的逻辑之后,完整脚本示例如下:
$ExcelObj = New-Object -comobject Excel.Application $ExcelObj.visible=$true #Open excel file $ExcelWorkBook = $ExcelObj.Workbooks.Open("C:\MyOwn\Scritps\ResultAllertButton.xlsx") #Copy last sheet, rename it and change position. $SelectedSourceList = $ExcelWorkBook.Worksheets.Item(3) $SelectedSourceList.Copy($SelectedSourceList) $ExcelActiveSheet = $ExcelWorkBook.ActiveSheet.Index $SelectedSourceList = $ExcelWorkBook.Worksheets.Item($ExcelActiveSheet) $SelectedSourceList.Name = "$date" for ($i=0; $i -le ($ExcelWorkBook.Worksheets.Count -1); $i++){ $lastsheet = $ExcelWorkBook.Worksheets($ExcelWorkBook.Worksheets.Count) $SelectedSourceList.Move([System.Reflection.Missing]::Value, $lastsheet) } #Add values in the cells $ExcelWorkBook.Worksheets.Item(4) $SelectedSourceList.Cells.Item(1, 1) = 'blablabla1' $SelectedSourceList.Cells.Item(2, 1) = "blablabla2: $date" $SelectedSourceList.Cells.Item(3, 1) = "blablabla3: $Responsible" if($result.DiferenceUsers.Count -ne $null) { foreach($obj in ($result.DiferenceUsers.Count -1)){ $SelectedSourceList.Cells.Item(27, 6) = $result.DiferenceUsers[4] } } # ------------------- 添加调整单元格大小的代码 ------------------- # 手动设置A列宽度和第1行高度 $SelectedSourceList.Columns.Item(1).ColumnWidth = 25 $SelectedSourceList.Rows.Item(1).RowHeight = 22 # 让B、C列自动适配内容 $SelectedSourceList.Columns.Item(2).AutoFit() $SelectedSourceList.Columns.Item(3).AutoFit() # 调整F列和第27行的大小 $SelectedSourceList.Columns.Item(6).ColumnWidth = 30 $SelectedSourceList.Rows.Item(27).RowHeight = 20 # --------------------------------------------------------------- # 可选:保存并关闭Excel(如果需要) # $ExcelWorkBook.Save() # $ExcelWorkBook.Close() # $ExcelObj.Quit() # [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelObj)
内容的提问来源于stack exchange,提问作者Catcher Rem
相关产品推荐
相关产品推荐

