- 论坛徽章:
- 0
|
目前面临以下数据结构(txt格式)
文件名:1.txt
1 2 3
item1 100 200 300
item2 300 400 450
文件名:2.txt
1 2
item1 500 600
item2 700 900
item3 1000 3000
第一行是年度,但是没有对应的说明。
字段、数据之间是用空格(或者制表符tab)隔开。
相关文件共有1000多个。
要求:用perl提取相应的年度/项目/数据信息,并将每个文件生成对应的xls文件如下。
1.xls
FileName Item year1 year2 year3
1 item1 100 200 300
1 item2 300 400 450
2.xls
Filename Item year1 year2
2 item1 500 600
2 item2 700 900
2 item3 1000 3000
我是Perl的初学者,参考论坛各位的程序建议,编写程序如下:
#!/usr/bin/perl
use Spreadsheet::WriteExcel;
#Specify the directory containing the files that you want to read
my $direct="e:\\test";
#Specify the directory containing the files that you want to save
my $dirOut="e:\\test1";
#If Windows "\\", if Mac "/";
my $slash='\\';
#The following two steps open the directory containing the files you plan to read
#and then stores the name of each file in an array called @data.
opendir(DIR1,"$direct")||die "Can't open directory";
my @New1=readdir(DIR1);
foreach $file(@New1)
{
# this step removes the default end of line character (\n)
# so the the entire file can be read in at once.
local $/;
open (SLURP, "$direct$slash"."$file") or die "can't open $file: $!";
#read the contents into file
$file = <SLURP>;
}
#close the filehandle called SLURP
close SLURP or die "cannot close $file: $!";
if ($file){
my @data = map [split], <$file>;
splice $data[0], 5, 2, join '_', @{$data[0]}[5,6];
my $xls = Spreadsheet::WriteExcel->new('"$dirOut$slash"."$file".xls');
my $ws = $xls->add_worksheet();
my $format = $xls->add_format();
$format->set_align('right');
my $i = 0;
for my $e (@data) {
my $j = 0;
map $ws->write( $i, $j++, $_, $format ), @$e;
$i++;
}
}
运行结果显示 can't open .: Permission denied at table_test2.pl line 21
请各位高手指教!
多谢! |
|