使用powershell删除excel文件中的额外行?

时间:2017-07-25 16:41:42

标签: excel powershell csv

我的任务是在公司拥有的SPLA服务器上自动执行部分日志记录过程。我的任务是更新,存档和删除旧文件,然后转到生成报告,通过电子邮件发送给部门。这项任务应该在每周结束时运行。

我认为powershell将是完成此任务的最佳选择。这是我第一次使用PowerShell,所以我有点学习。

我的问题:

是否可以循环使用Excel工作表并使用此脚本删除未使用的行?

我的情况是,如果有两个空行 - >删除一行并继续

我从日志中获取信息并将其拆分为CSV,然后将CSV转换为Excel格式化。

Sample of the Excel spreadsheet, others vary in excess rows between information

Get-ChildItem C:\ScriptsDirectory1\*.log | foreach{

$input = Get-Content $_.FullName                                                #Initialize input
$a = Get-Date                                                                   #Save the current date (for if/else wrapper)
#=============================================#
#              File Name Changer              #
#=============================================#

$x = $_.LastWriteTime.ToShortDateString()                                       #Save a temp variable with the LastWriteTime and send it to a string

$new_folder_name = Get-Date $x -Format yyyy.MM.dd                               #Create a new folder that contains the string information

$des_path = "C:\Archive\ArchivedLogs\$new_folder_name"                          #Send the new folder to the archive directory
#=============================================#


$data = $input[1..($input.Length - 1)]                                          #Initialize Array and set it to the length of the input file.
$maxLength = 0


$objects = ForEach($record in $data) {                                          #Loop through each object within the array

    $split = $record -split ": "                                                #Split objects within array at the ": " string
    If($split.Length -gt $maxLength){
        $maxLength = $split.Length
    }

    $properties = @{}

    For($i=0; $i -lt $split.Length; $i++) {                                     #Adds the split information to the strings array
        $properties.Add([String]($i+1),$split[$i])
    }

    New-Object -TypeName PSObject -Property $properties 
}
$objects | format-table

$headers = [String[]](1..$maxLength) 

$objects | 
Select-Object $headers |

Export-Csv -NoTypeInformation -Path "C:\Archive\CSVReports\$new_folder_name.csv"#Export CSV path using the new folder name to prevent overwrite

if (test-path $des_path){                                                       #Test if the path exists, and fill the directory with the file to be archived

    move-item $_.fullname $des_path 
    } else {
    new-item -ItemType directory -Path $des_path
    move-item $_.fullname $des_path 
    }
} #End of Parser

#===============================================================================#
#======================================#========================================#
#===============================================================================#
#                   File Archiver and Zipper (After Parse/CSV)                  #
#===============================================================================#
#======================================#========================================#
#===============================================================================#
$files = Get-ChildItem C:\Archive\ArchivedLogs                                  #Fill the $files variable with the new files in the Archive directory

#********************************#
#Loop Through and Compress/Delete#
#********************************#
foreach ($file in $files) {

    Write-Zip $file "C:\Archive\ArchivedLogs\$file.zip" -Level 9                #Write compressed file

} #End of Archiver
Remove-Item C:\Archive\ArchivedLogs\* -exclude *.zip -recurse                   #Remove the un-needed files within the archive folder    
#Run the Formatting and Conversion script for the CSV-to-XLSX
#C:\ScriptsDirectory1\Script\TestRunner1.ps1 #<---Can be Ran using a Invoke call
#===============================================================================#
#======================================#========================================#
#===============================================================================#
#                          CSV to XLSX Format/Conversion                        #
#===============================================================================#
#======================================#========================================#
#===============================================================================#
Get-ChildItem C:\Archive\CSVReports | foreach{
$excel_file_path = $_.FullName                                                  #Create the file path variable to initialize for formating
$Excel = New-Object -ComObject Excel.Application                                #Start a new excel application

$Excel.Visible = $True
$Excel.DisplayAlerts=$False
$Excel_Workbook = $Excel.Workbooks.Open($excel_file_path)                       #Create workbook variable and open a workbook in the path
$FileName = $_.BaseName                                                         #Save the base file name of the current value
$Excel.ActiveSheet.ListObjects.add(1,$Excel_Workbook.ActiveSheet.UsedRange,0,1) 
$Excel_Workbook.ActiveSheet.UsedRange.EntireColumn.AutoFit()

$SPLA1wksht = $Excel_Workbook.Worksheets.Item(1)                                #Create the new Sheet (SPLA1wksht)
#*******************************************************#
#                 Formating for Title Cell              #
#*******************************************************#
$SPLA1wksht.Name = 'SPLA Info Report'                                           #Change worksheet name
$SPLA1wksht.Cells.Item(1,1) = $FileName                                         #Title (Date of log) in cell A1
$SPLA1wksht.Cells.Item(1,2) = 'SPLA Weekly Report'                              #Title for all Excel reports
$SPLA1wksht.Cells.Item(1.2).Font.Size = 18
$SPLA1wksht.Cells.Item(1.2).Font.Bold=$True
$SPLA1wksht.Cells.Item(1.2).Font.Name="Cambria"
$SPLA1wksht.Cells.Item(1.2).Font.ThemeFont = 1
$SPLA1wksht.Cells.Item(1.2).Font.ThemeColor = 5
$SPLA1wksht.Cells.Item(1.2).Font.Color = 8210719
#*******************************************************#

#************************************#
#        Adjust and Merge Cell B1    #
#************************************#
$range = $SPLA1wksht.Range("b1","h2")
$range.Style = 'Title'

$range = $SPLA1wksht.Range("b1","g2")

$range.VerticalAlignment = -4108                                                #Center align vertically (Value -4108 is center)
#************************************#

#***********************************************************************#
#                     Horizontal Centering for all cells                #
#***********************************************************************#
$ColumnRange = $SPLA1wksht.Range("a1","a500").horizontalAlignment =-4108        #Center all cells in this range as -4108
$ColumnRange = $SPLA1wksht.Range("b1","b500").horizontalAlignment =-4108

#**********************************************#
#               Delete Blank Rows    Inneffective- Logs that have different 
#data end up with a different amount of rows and offsets this deletion          
#                                # This method deletes the first row then 
#moves onto
#**********************************************#                                # the next-in-line blank lines and deletes the one
#$SPLA1wksht.Cells.Item(2,1).EntireRow.Delete() #                                # line until the blank spots are in perfect format
                                               #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() #
                                               #
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()#
                                               #
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()#
                                               #
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()#
#**********************************************#

#*****************************************************************#
#               Final Export as a CSV-to-XLSX file                #
#*****************************************************************#
$Excel_Workbook.SaveAs("C:\Archive\ExcelReports\$FileName.xlsx",51)             #Save the file in the proper location
$Excel_Workbook.Saved = $True
$Excel.Quit()
# Find a way to optimize this process

#Potential optimization places:
# 1.) Don't open and close excel file and instead just write changes and save
# 2.) Change way empty rows are formatted instead of seperate calls each time
} #End of Format/Converter
#******End******#

#---------------#--#--------------#
#---------------------------------#
#    What to Add to the Script    #
#---------------------------------#
#---------------#--#--------------#
# -[/] <-Complete -[] <- Incomplete
# -[] Archive or delete CSV Files
# -[] Add a If/Else statement that checks if files are >7 days old
# -[] Compile a weekender report that indicates any SPLA programs changed to keep compliance
# -[] Filter for only SPLA files (Need a list)
# -[] Loop through CSV/Excel file and delete empty rows

以下代码贯穿整个程序:

for($i = 350 ; $i -ge 0 ; $i--) {
    If ($SPLA1wksht.Cells.Item($i, 1).Text-eq "") {
        $Range = $SPLA1wksht.Cells.Item($i, 1).EntireRow
        [void]$Range.Delete()
        echo $i
     }
    If ($SPLA1wksht.Cells.Item($i, 2).Text-eq "") {
        $Range = $SPLA1wksht.Cells.Item($i, 2).EntireRow
        [void]$Range.Delete()
        echo $i
     }
    If($i -eq 2){ break;} 
}

1 个答案:

答案 0 :(得分:0)

这应该是相对简单的

$file = C:\path\to\file.csv
$csv = Import-Csv $file

foreach($row in $csv) {
     # logic to delete row
     # $csv is an array, so you can could make the row = null to delete it
}
# spit out updated excel sheet
Export-Csv | $csv -NoTypeInformation