perl - 将存储的字符串打印到单个单元格中的 xls
问题描述
我有一个存储有字符串的数组,我从文本文件中提取该数组并希望在单个单元格中的 xls 上打印。下面的命令能够打印在同一列但分开的行中。寻找一种在单个单元格中打印的方法。
#!/usr/bin/perl
use strict;
use warnings;
use Spreadsheet::WriteExcel;
my $workbook = Spreadsheet::WriteExcel->new("result.xls");
my $wrksheet = $workbook->add_worksheet("summary");
$wrksheet->write_col(1,0,[@{read_out_your_file_misc("temp_stage.txt")}]);
$workbook->close() or die "Error closing file: $!";
sub read_out_your_file_misc {
my $content_of_file = [];
open my $fhh, '<', shift() or die "can't open file:$!";
while (<$fhh>) {
chomp;
#push @{$content_of_file}, $_, $/;
push @{$content_of_file}, $_;
}
return $content_of_file;
}
解决方案
如果您提供的数组中包含多个元素,则0
( A
) 列中的多行将由 填充write_col
。您可以join
通过数组中的元素来解决这个问题。如果这是您经常使用的模式,您甚至可以根据需要更改read_out_your_file_misc
函数以返回数组或标量。
sub read_out_your_file_misc {
my $filename = shift or die "ERROR: read_out_your_file_misc needs a filename";
my $delim = shift || ','; # make the default delimiter a comma
open my $fhh, '<', $filename or die "ERROR: $filename: $!";
my @content_of_file = <$fhh>; # read the whole file at once
close $fhh;
chomp @content_of_file; # chomp the complete array
if(wantarray) { # return an array if that's wanted
@content_of_file;
} else { # else return it as a scalar with $delim between elements
join($delim, @content_of_file);
}
}
现在根据接收变量的类型,函数的行为会有所不同。
以标量形式获取文件内容并仅填充 A2:
my $result = read_out_your_file_misc('temp_stage.txt');
$wrksheet->write_col(1, 0, [$result]);
以数组形式获取文件内容并从 A4 向下填充:
my @result = read_out_your_file_misc('temp_stage.txt');
$wrksheet->write_col(3, 0, \@result);
推荐阅读
- d3.js - 如何混合有用的自动生成的记号(),同时还指定您希望记号间隔下降到的最低粒度
- python - “启动器中的致命错误:”使用 pip 或烧瓶时
- c# - 如何使用公共 void 方法但私有成员测试代码?
- powerbi - powerBI 中的分组条形图
- python - 如何在测试服务器时模拟来自集成服务的响应
- java - JAXB 注释问题
- html - CSS 类优先级以及为什么我必须使用 !important 覆盖?
- javascript - 如何构建 JS 应用程序,将所有资产合并到单个文件组件中但不包装到 webpack 模块中
- junit - 为什么 org.apache.commons.lang.StringUtils.isBlank() 为空值和空值返回 false
- python - H5Py 和存储