Изменения формата временной метки Powershell в Excel - PullRequest
0 голосов
/ 29 апреля 2020

Я создаю функцию, которая возвращает дату за последние 6 месяцев, позволяет выбрать одну и добавляет ее к столбцу Дата в формате MMM / YY. Я использую это в GUI, и это показывает это так:

enter image description here

Каким-то образом это работает только в октябре месяце. Что происходит не так здесь ??

enter image description here

Код, который я использую:

$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```

1 Ответ

1 голос
/ 29 апреля 2020

Прежде всего, вам нужно проверить, что нужно вашему 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() 
...