【发布时间】:2020-04-30 16:41:57
【问题描述】:
为了代码的可读性,我想将我的 Excel 内容移动到一个函数中,并让工作表对象在我的程序处理内容时可用于写入单元格值。如何调用创建 Excel 电子表格并返回工作表引用的函数,以便我可以继续访问我创建的打开/活动 Excel 应用程序对象?
Function Create-Excel-Spreadsheet() {
# open excel
$excel = New-Object -ComObject excel.application
$excel.visible = $True
# add a worksheet
$workbook = $excel.Workbooks.Add()
$xl_wksht= $workbook.Worksheets.Item(1)
$xl_wksht.Name = 'Cut-off' #give the worksheet a name
#Create a Title for the first worksheet and adjust the font
$title_row = 1
$xl_wksht.Cells.Item($title_row, 1)= 'Cut-off Processing Ran ' + $startday + ' at ' + $starttime_str
#merging a few cells on the top row to make the title look nicer
$MergeCells = $xl_wksht.Range("A1:Q1")
$MergeCells.Select()
$MergeCells.MergeCells = $true
#formatting the title and giving it a font & color
$xl_wksht.cells($title_row, 1).HorizontalAlignment = -4108 # center the title
$xl_wksht.cells.Item($title_row,1).Font.Size = 18
$xl_wksht.cells.Item($title_row,1).Font.Bold = $True
$xl_wksht.cells.Item($title_row,1).Font.Name = "Cambria"
$xl_wksht.cells.Item($title_row,1).Font.ThemeFont = 1
$xl_wksht.cells.Item($title_row,1).Font.ThemeColor = 4
$xl_wksht.cells.Item($title_row,1).Font.ColorIndex = 55
$xl_wksht.cells.Item($title_row,1).Font.Color = 8210719
$xl_wksht.cells.Item($title_row,1).Font.Color = 8210719
$xl_wksht.Rows[$title_row].RowHeight = 39
$xl_wksht.Rows[$title_row].VerticalAlignment = 2
#create the column headers
$header_row = 2
$data_row_start = 3
$xl_wksht.Rows[$header_row].WrapText = $True
$xl_wksht.Rows[$header_row].Font.Bold = $True
$xl_wksht.Rows[$header_row].columnWidth = 12.57
$xl_wksht.Rows[$header_row].HorizontalAlignment = -4108
$xl_wksht.cells.Item($header_row, 1).value2 = 'Current Load Date'
$xl_wksht.Columns[1].HorizontalAlignment = -4108
$xl_wksht.Columns[1].NumberFormat = "@"
$xl_wksht.cells.Item($header_row, 2).value2 = 'Export File Type'
$xl_wksht.Columns[2].columnWidth = 26
$xl_wksht.cells.Item($header_row,3).value2 = 'File Name to Downloaded'
$xl_wksht.Columns[3].columnWidth = 37
$xl_wksht.cells.Item($header_row,4).value2 = 'Source Path'
$xl_wksht.Columns[4].columnWidth = 23
return $xl_wksht
}
【问题讨论】:
标签: excel function powershell reference