天天看點

Perl實作将将.txt中内容寫入到excel中

在處理存于txt中的大資料時,檢視非常不友善,可以考慮寫入到excel中。以下是一個簡單的用perl實作的寫入excel的程式。

#寫檔案到excel
#輸入:待寫入到excel表中的.txt檔案
#輸出:excel檔案,注意要用絕對路徑

#####################################################
use strict;
use Win32;
use Cwd;
use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;                                # die on errors...

# get already active Excel application or open new
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
    || Win32::OLE->new('Excel.Application', 'Quit');
use Encode;

my $infile1="a.txt";
my $outexcel1="E:/PerlCode/cyliu/a.xlsx";
open IN1,"$infile1"
or die "could not open the input file!";

my $Book = $Excel->Workbooks->Open("$outexcel1") or die "Could not open the $outexcel1 !!!\n";
my $Sheet = $Book->Worksheets(1);
my $row=0;
my %hangye;
my %num;
my %word;
my %word1;
while(my $aline=<IN1>)
{
  $row++;
  print $row."\n";
  $aline=~s/\n$//;
  my @array=split(/\t/,$aline);

  $Sheet->Cells($row,1)->{'Value'}=$array[0];
  $Sheet->Cells($row,2)->{'Value'}=$array[1];

  $Sheet->Cells($row,3)->{'Value'}=$array[2];
  $Sheet->Cells($row,4)->{'Value'}=$array[3];#$big.":".$name{$big};
  $Sheet->Cells($row,5)->{'Value'}=$array[4];
	$Sheet->Cells($row,6)->{'Value'}=$array[5];
}
$Book->Close;           

繼續閱讀