我正在构建一个函数,该函数返回最近6个月的日期,让您选择一个日期,并将其附加到MMM / YY格式的Date列中。我在GUI中使用它,它显示如下:
以某种方式仅在十月份有效。这里出了什么问题?
我正在使用的代码:
$dateList=-6..0 |ForEach-Object{ (Get-Date).AddMonths($_).ToString('MMM/yy') }
$txtDateList.Items.Clear()
foreach ($textdate in $dateList) {
$txtDateList.Items.Add($textdate)
}
$txtDate = $txtDateList.SelectedItem
$sheet.cells.item($row, $colDate.Column).value = $txtDate```
首先,自定义格式日期单元格时,需要检查Excel需要什么。我的(Dutch Excel)想要MMM-jj
格式,但更可能需要MMM-yy
。
将日期插入为日期时间对象,完成后,格式化日期列。
类似这样的东西:
$file = 'D:\Test\Map1.xlsx'
$today = Get-Date
# set the reference date to be the first day of this month,
# with time part set to 00:00:00 (midnight)
$refDate = (Get-Date -Year $today.Year -Month $today.Month -Day 1).Date
# Build an array of dates from the reference date, so all will be on the 1st day of the month
$dateList = -6..0 | ForEach-Object{ $refDate.AddMonths($_) }
# create an Excel COM object and open the file
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$workbook = $excel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item(1)
$row = 1 # starting row
$col = 1 # the column where the dates are inserted
# insert the dates
foreach ($date in $dateList) {
# Excel will NOT regard this as Date if a formatted string is entered.
$sheet.Cells.Item($row++, $col) = $date
}
# format the entire date column
$sheet.Columns.Item($col).EntireColumn.NumberFormat = "MMM-yy" # This is LOCALIZED, check your Excel!
# save, close and clean-up
$workbook.Save()
$workbook.Close()
$excel.Quit()
# clean-up used Excel COM objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()