perl模块Excel::Writer::XLSX进行txt2xlsx转换

davidliu00 2019-12-10

#!usr/bin/env perl
use strict;
use warnings;
use File::Spec;
use Getopt::Long;
use Excel::Writer::XLSX;

#检测 -> 脚本输入
my ($input_txt, $output_path, $if_help);

GetOptions(
"input_txt|i=s" => \$input_txt,
"output_path|o=s" => \$output_path,
"help|h" => \$if_help,
);

die help() if (defined $if_help or (not defined $input_txt));

################################主程序###########################

########
#创建excel文件与sheet表
########
my $workbook = Excel::Writer::XLSX->new( ‘DFI_15_30.VS.DFI_15_ABN.xlsx‘);
my $worksheet = $workbook->add_worksheet(‘DFI_15_30.VS.DFI_15_ABN‘);

########
#开始处理文本
########

my %format = format_excel($workbook); #获取Excel格式内容
open FILE, $input_txt or die "The input_txt file doesn‘t exist!\n";

########
#处理标题行格式
########
my $head = <FILE>;
$head =~ s/[\r\n]//g;
my @head = split /\t/, $head;
$worksheet->set_row(0, 60); #标题行设置:行宽60
foreach (0..$#head) {
    $worksheet -> write (0, $_, $head[$_], $format{‘title‘}); #格式化第一行内容
}

########
#处理数据行内容
########

my @special = (‘P-value(Ttest)‘, ‘P-value(Utest)‘, ‘P-value(Logistic)‘);#需要筛选的p_value存在一个数组里
my $row = 1;
while (<FILE>) {
$_ =~ s/[\r\n]//g;
my @data = split /\t/;
    foreach my $col (0..$#data) {
        my $type = "normal";
        foreach (@special) {
            $type = "special" if ($head[$col] eq $_ and $data[$col] =~ /\d/ and $data[$col] < 0.05);
        }
            #$type = "special" if ($head[$col] ~~ @special and $data[$col] =~ /\d/ and $data[$col] < 0.05);
        $worksheet -> write($row, $col, $data[$col], $format{$type}); #格式化数据行内容
     }
    $row ++;
}

close FILE;

################################子函数###########################

sub format_excel {
my ($workbook) = @_;
my %format = ();
#第一行(标题行设置:背景色黄色、上下左右居中)
$format{"title"} = $workbook->add_format();
$format{"title"}->set_bg_color(‘yellow‘);
$format{"title"}->set_align(‘center‘);
$format{"title"}->set_align(‘vcenter‘);
$format{‘title‘}->set_border();
#其它行(上下左右居中)
$format{"normal"} = $workbook->add_format();
$format{"normal"}->set_align(‘center‘);
$format{"normal"}->set_align(‘vcenter‘);
$format{"normal"}->set_border();
#特殊列处理(P-value(Ttest)、P-value(Utest)、P-value(Logistic)这三列P值<0.05的表格背景色设为橘黄色#fac090)
$format{"special"} = $workbook->add_format();
$format{"special"} ->set_align(‘center‘);
$format{"special"} ->set_align(‘vcenter‘);
$format{"special"} ->set_bg_color("#fac090");
$format{"special"}->set_border();

return %format;
}

sub help{
my $info = "
Program: txt转换为excel
Version: 2019-11
Contact: *

Usage: perl ".(File::Spec->splitpath(File::Spec->rel2abs($0)))[2]." [options]

Options:
--txt/-i txt文件
--output_path/-o 输出路径
--help/-h 查看帮助文档
\n";
return $info;
}

相关推荐