简体   繁体   中英

Inserting Empty Row into a Excel Document

I have a excel document that I am editing with perl OLE automation and I have run into a problem. I need to enter an empty row in between two rows that already contain data, kind of like appending it to the file but not at the end of the file. I don't want to have to rewrite the entire file using perl either. How would I go about doing this?

Thanks

One thing that always helps me when I am automating Excel with Perl & Win32::OLE is to create a macro in Excel capturing exactly what I am trying to accomplish first. From there I can view the VB code and usually convert that to Perl relatively easily.

For example, in an open Excel 2010 file:

  1. View -> Macros -> Record New Macro
  2. Click OK
  3. Right click somewhere on the sheet to insert a new row
  4. View -> Macros -> Stop Recording
  5. View -> Macros -> View Macros, click edit

From this, I could write code, for example:

#!c:/perl/bin/perl.exe

use strict;
use warnings;

use Win32::OLE;

my $excel = Win32::OLE->new( 'Excel.Application' )
    or die "Could Not Start Excel.\n";
$excel->{ 'Visible' }           = 1;
$excel->{ DisplayAlerts }       = 0;
$excel->{ SheetsInNewWorkBook } = 1;
my $workbook = $excel->Workbooks->Add;
my $sheet = $workbook->Sheets( 1 );

$sheet->Range( 'A1' )->{ Value } = 'Data 1';
$sheet->Range( 'A2' )->{ Value } = 'Data 2';
$sheet->Range( '2:2' )->Select(); #Select Entire 2nd Row
$sheet->Range( '2:2' )->Insert( {
    'Shift'      => -4121, #xlDown
    'CopyOrigin' => 0,     #xlFormatFromLeftOrAbove
} );

__END__

Also, here is a list of a bunch of the Excel enumerations: http://www.datapigtechnologies.com/downloads/Excel_Enumerations.txt

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM