如何用Perl读取Excel文件属性(作者、标题等)
读取Excel文档属性的Perl解决方案
针对你的需求,确实有对应的Perl模块可以读取Excel的作者、标题、主题等属性,分两种文件格式来说明:
XLSX格式(Office Open XML)
推荐使用Spreadsheet::XLSX或者Excel::Reader::XLSX,这两个模块都能直接读取文档属性。
用Spreadsheet::XLSX的示例:
use strict; use warnings; use Spreadsheet::XLSX; my $xlsx = Spreadsheet::XLSX->new('target_file.xlsx'); my $props = $xlsx->{Properties}; print "作者: ", $props->{Creator}, "\n"; print "标题: ", $props->{Title}, "\n"; print "主题: ", $props->{Subject}, "\n"; # 还能获取创建时间、修改时间等其他属性
用Excel::Reader::XLSX的示例:
use strict; use warnings; use Excel::Reader::XLSX; my $reader = Excel::Reader::XLSX->new(); my $workbook = $reader->open('target_file.xlsx'); my $props = $workbook->properties; print "作者: ", $props->creator, "\n"; print "标题: ", $props->title, "\n"; print "主题: ", $props->subject, "\n";
XLS格式(旧版二进制格式)
Spreadsheet::ParseExcel本身不支持读取属性,但可以结合OLE::Storage_Lite来提取——因为XLS本质是OLE容器文档,属性存在SummaryInformation流里:
use strict; use warnings; use OLE::Storage_Lite; my $ole = OLE::Storage_Lite->new('target_file.xls'); my $pps = $ole->getPpsSearch(1, "\x05SummaryInformation"); if ($pps) { my $data = $pps->{Data}; # 解析流数据提取属性,偏移和格式对应OLE的SummaryInformation结构 my ($title, $subject, $author) = unpack('x64 Z* Z* Z*', $data); print "作者: $author\n"; print "标题: $title\n"; print "主题: $subject\n"; }
补充:Spreadsheet::ParseExcel确实没有内置读取文档属性的方法,所以需要根据你的Excel文件格式选择上述对应方案。
内容的提问来源于stack exchange,提问作者Alex Gudkoff
相关产品推荐
相关产品推荐

