不使用EXCEL编辑CSV

时间:2019-05-22 20:34:50

标签: powershell csv

我需要通过将数据的第一列向下移动1行来编辑.CSV文件。然后将第一列中的最后一个值移到顶部。我不使用该怎么办

$objExcel = New-Object -ComObject Excel.Application

1 个答案:

答案 0 :(得分:0)

尽管我不知道为什么要旋转其中一列中的值,但这是无需Excel即可实现的。

从您的评论中,我收集到的CSV文件没有标题,而仅包含数据行。 因此,以下在导入数据时添加了标头。

假设您的csv文件如下所示:

Clothing Rental,Chicago Illinois,1,25
Clothing Purchase,Dallas Texas,2,35
Clothing Free of Charge,Phoenix Arizona,3,45

然后执行以下操作:

$data = Import-Csv -Path 'D:\yourdata.csv' -Header 'Stuff','City','Number','InStock'    # or add whatever headers you like
# get the first column as array of values
$column1 = $data.Stuff
# rotate the array values
switch ($column1.Count) {
    1 { Write-Host "Nothing to do here. There is only one row of data.."; break}
    2 { 
        # swap the values
        $data[0].Stuff,$data[1].Stuff = $data[1].Stuff,$data[0].Stuff
        break
    }
    default {
        $newColumn1 = @($column1[-1]; $column1[0..($column1.Count -2)])
        # re-write the first column in the data
        for ($i = 0; $i -lt $newColumn1.Count; $i++) {
            $data[$i].Stuff = $newColumn1[$i]
        }
    }
}

# output on screen
$data

# output to new CSV file WITH headers
$data | Export-Csv -Path 'D:\your_rotated_data.csv' -NoTypeInformation -Force

# output to new CSV file WITHOUT headers
$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content -Path 'D:\your_rotated_data.csv' -Force

运行此命令后屏幕上的输出看起来像

Stuff                   City             Number InStock
-----                   ----             ------ -------
Clothing Free of Charge Chicago Illinois 1      25     
Clothing Rental         Dallas Texas     2      35     
Clothing Purchase       Phoenix Arizona  3      45

您会看到第一列(“内容”)中的所有值均已旋转,即,最后一个值现在位于顶部,而其他值已向下移。

相关问题