Sorting excel CSV by column, saving and closing - with batch or powershell

不问归期 提交于 2019-12-25 01:34:04

问题


I am using a bat file to open a daily-generated Excel file named 'YYYYMMDD_foo.csv' using batch - this works fine, but I am also trying to group sort the Excel file by one of it's columns - say Column C (Dept.).

ID, Name, Dept.
001, Greg, Maths
002, Sue, Operations
003, Bob, Academics
004, Joan, Operations

How could I accomplish this sort in batch, so that the file is opened, and then sorted as such?

ID, Name, Dept.
003, Bob, Academics
001, Greg, Maths
002, Sue, Operations
004, Joan, Operations

Thank you kindly

EDIT: I have attempted to find a solution with Powershell and with Batch - I will post my scripts below and hopefully with will reopen my question.

Powershell:

$FilePath = "C:\exceltest\20191203Records.csv"

$rawDate = Get-Date
$year = $rawDate.toString('yyyy')
$month = $rawDate.toString('mm')
$day = $rawDate.toString('dd')



$objExcel = New-Object -ComObject Excel.Application

$objExcel.Visible = $true
$objExcel.DisplayAlerts = $true

$WorkBook = $objExcel.Workbooks.Open($FilePath)

$WorkBook | Sort-Object Program

$WorkBook.Save()

Start-Sleep -s 30

Batch:

@echo off

SET dY=%DATE:~0,4%
SET dM=%DATE:~5,2%
SET dD=%DATE:~8,2%
SET searchString=%dY%%dM%%dD%Records.csv
SET thePath=C:\exceltest\

echo %thePath%%searchString%

start Excel.exe %thePath%%searchString%
PAUSE

回答1:


There is no need to use Excel to sort the List. This can be done directly with Powershell. Below example reads the file, sort it by column "Dept." and writes it into an new CSV-File that can be opened in Excel directly.

#Make sure to use MM for Month, mm is Minutes
$dateString = (Get-Date).ToString('yyyyMMdd')

$filepath= "C:\temp\" + $dateString + "_foo.csv"
$list = Import-Csv -LiteralPath $filepath -Delimiter ","

$outPutFilePath = "C:\temp\"+$dateString+"_sorted.csv"

#sort the List and Export it into CSV-File. Use ; so excel will directly open it correctly
$list | Sort-Object -Property "Dept." | Export-Csv -LiteralPath $outPutFilePath -Delimiter ";" -NoTypeInformation


来源:https://stackoverflow.com/questions/59182297/sorting-excel-csv-by-column-saving-and-closing-with-batch-or-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!