Прежде всего, вам нужно проверить, что нужно вашему Excel при пользовательском форматировании ячейки даты. Мой (Голландский 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()