Powershell excel удалить строку

You can’t use OleDB for deleting data from Excel document. As per MSDN docmentation:

Although the Jet OLE DB Provider allows you to insert and update
records in an Excel workbook, it does not allow DELETE operation

What you can do is use Exel’s COM interface to delete rows. Remember to release COM object too. Like so,

$file = c:tempMyExcelFile.xls
# Star Excel, hide window
$excel = new-object -com Excel.Application -Property @{Visible = $false} 
$workbook = $excel.Workbooks.Open($file) # Open the file
$sheet = $workbook.Sheets.Item(1) # Activate the first worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row

$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM

  • Remove From My Forums
  • Question

  • Hi everyone.  Again, I am having trouble working with Excel via Powershell.  I am slowly learning my way around but cannot correctly utilize any information I may find that helps me get the correct results.  So far I am working on a project
    at work that is automating the testing of our build process.  I am «borrowing» an excel sheet that I will save to my local machine to save as CSV.  However, before saving to CSV I need to remove the empty rows.  Unfortunately, the cells are
    not really blank but still contain links to the server I pulled the workbook from.

    I’m not sure what is easiest to do, but the «blanks» are within this range: A49:F320  and this is the range I’d like to delete.  The code I am currently working with is:

    $Excel = new-object -comobject excel.application

    $Excel.Visible = $False

    $Workbook = $Excel.Workbooks.Open($BuildXLS)

    $Worksheet = $Workbook.Worksheets.Item(1)

    $i = 1

        If ($Worksheet.Cells.Item($i, 1).Value() -eq »  «) {

            $Range = $Worksheet.Cells.Item($i, 1).EntireRow

            $a = $Range.Delete()

            $i -= 1

        }

        $i += 1

     Incidentally, mjolinor helped with an earlier issue parsing through the CSV.  It was only after looking at the output that I discovered my real issue is working with the Excel.

    $data = import-csv $csv | Where-Object {$_.juris -ne » «}

    #format Juris-Version results

    foreach ($line in $data)

    {

      if ($line.juris -eq ‘US’){$line.Version = $FedVerNum}

       else {$line.Version = $ContentVer}

           write-output $line.juris$line.version | Out-File -Append «C:1_JurisVersion.txt»

      }

    The output from that help session looks like:

    US

    $FedVerNum

    State

    $ContentVer

    Is there a away I can get this to read as

    US $FedVerNum

    state $ContentVer

    state $ContentVer

    state $ContentVer

    Many thanks for the help and expertise!

Answers

  • Give this a try:

    $xlCellTypeLastCell = 11

    $xl = New-Object -comobject excel.application
    $xl.Visible = $true
    $xl.DisplayAlerts = $False
    $wb = $xl.Workbooks.Open(«C:ScriptsBuildXLS.xls») # <— Change as required!
    $ws = $wb.Worksheets.Item(1)
    $used = $ws.usedRange
    $lastCell = $used.SpecialCells($xlCellTypeLastCell)
    $row = $lastCell.row

    for ($i = 0; $i -le $row; $i++) {
        If ($ws.Cells.Item($i, 1) = » «) {
            $Range = $ws.Cells.Item($i, 1).EntireRow
            $Range.Delete()
            $i = $i — 1
        }
    }

    Check my Excel Cookbook at http://olddogsblog.spaces.live.com

    • Proposed as answer by

      Tuesday, June 15, 2010 4:49 PM

    • Marked as answer by
      notmyernie
      Tuesday, June 15, 2010 7:24 PM

I had a project to automate the import of a large number of excel files via SSIS into SQL 2012. Many of the files had different headers, but they all had a column header row that preceded the data.

On some of the files, the header row started on row 2, 3, 4, or 5, and on some others, the first two or three columns were entirely blank. What a pain, right?

One saving advantage that I identified in this proprietary set of excel files: each of the datasets begins with a column headed «Identifier», so that is the cell that I want to end up in cell [A1]. That was definitely key to making this work and easily identifying when my header row began.

I automated cleaning up these spreadsheets with the following PowerShell script

Param([string]$wbname)

Try
{
$err1 = 0;
#testing only #$wbname = "E:foo.xls"

$xl = New-Object -comobject Excel.Application
$xl.DisplayAlerts = $False

$wb = $xl.Workbooks.open($wbname)
$sheet = $wb.Sheets.Item(1)

#delete columns
while( ($sheet.Cells.Item(1,1).Text -eq "") -and ($sheet.Cells.Item(2,1).Text -eq "") -and ($sheet.Cells.Item(3,1).Text -eq "")){[void]$sheet.Cells.Item(1,1).EntireColumn.Delete()}

#delete rows
while( ($sheet.Cells.Item(1,1).Value() -NotLike "Identifier") -and ($sheet.Cells.Item(1,2).Value() -NotLike "Identifier")){[void]$sheet.Cells.Item(1,1).EntireRow.Delete()}

#cleanup
$wb.Close($true)
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Remove-Variable xl

}
Catch
{
$err1 = 1;
}
Finally
{
if($err1 -eq 1)
{
#Write-Output "99";
#Write-Output $_.Exception.Message;

$stream = [System.IO.StreamWriter] "e:error.txt"
$stream.WriteLine($Error[0].InvocationInfo.PositionMessage)
$stream.WriteLine($wbname)
$stream.close()

[Environment]::Exit("99");
}
Else
{
#Write-Output "0";
[Environment]::Exit("0");
}

}

The two while loops are where the customization was for my particular set of problematic Excel spreadsheets, but the general structure of the code is where you can change it up for yourself.

The last four lines are cleanup — while the last might not be very important, the second-to-last line is pretty important to make sure the stick COM object goes away. Explained much better here: http://technet.microsoft.com/en-us/library/ff730962.aspx

In order to put this in sequence in my SSIS package, I used the Execute Process Task. Screenshots below:

Unfortunately the client server I was working for here only had PowerShell 1.0 installed, but from what I understand, this should apply to PowerShell 2.0 and 3.0. I’m open to anyone who has any insight there.

(click to enlarge the below images)


The argument passed to the PowerShell file includes the full path to the Excel file. (I removed the paths from this actual client implementation.)

I’m open to feedback on this, wonder if anyone else has encountered a similar issue. Obviously, the best solution would have been to modify the process that generates these maddeningly inconsistent excel files.

I have a csv file which has a series of pin-codes in column A but the first row/cell (A1) is empty and I need to delete the whole row using Powershell,
any ideas?

I have tried this but it did nothing!

(gc C:TEMPtestNewGroup17.csv) | ? {$_.trim() -ne "" } | set-content C:TEMPtestNewGroup18.csv

Burgi's user avatar

Burgi

6,45714 gold badges40 silver badges52 bronze badges

asked Mar 15, 2019 at 7:19

user1007984's user avatar

2

This will skip the first row:

       $myFile = @(import-csv NewGroup17.csv -Encoding default)
       $i = 0
       foreach ($row in $myFile){
          if($i -gt 0){
          $myNewFile += $row
          }
          $i++
       }
       $myNewFile | export-csv (NewGroup18.csv) -NoTypeInformation -Encoding default

answered Mar 15, 2019 at 17:02

Brian's user avatar

BrianBrian

7013 silver badges8 bronze badges

I am still very new to powershell and feel like this might be a simple question, but I am stuck on my program trying to filter my excel spreadsheet, and then delete the filtered rows.

ideally I would like to filter for all the rows that do NOT say «NO DATA» in column A starting at Row 3.
once I have all of those rows I would like to delete them all.
Then bring back all the rows that have «NO DATA»

what I cant figure out is how to write the script so that the filter starts at row 2, and how to filter for all the rows that do NOT say «NO DATA»

$worksheet.usedrange.autofilter(1, -ne "NO DATA", 3)
$worksheet.usedrange.offset(1,0).specialcells(12).Entirerow.Delete() 
$worksheet.ShowAllData()

when I try what seems logical to me I get 2 errors, one is «missing expression» after the’,’ before -ne, and the other is «unable to get the Auto filter property of the range class» referring to the (Column#, Text, Row#) portion.

$worksheet.usedrange.autofilter(1, "NO DATA", 2)
$worksheet.usedrange.offset(1,0).specialcells(12).Entirerow.Delete() 
$worksheet.ShowAllData()

This code works but gives me the wrong data set (I’m left with everything I wanted deleted, and it still filters from row 1 and not row 2.

any help would be great.

Like this post? Please share to your friends:
  • Powershell excel сохранить как
  • Power query для excel возможности
  • Powershell excel открыть файл
  • Power query для excel for mac
  • Power query для excel 365