用 Spreadsheet::ParseExcel处理中文excel文件

本文介绍如何使用Perl语言和Spreadsheet::ParseExcel模块解析含有中文的Excel文件,并提供了详细的步骤和示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要用的模块:
Spreadsheet::ParseExcel
Unicode::Map
IO-stringy
OLE-Storage_Lite

其中IO-stringy,OLE-Storage_Lite为运行的必要包
Spreadsheet::ParseExcel是解析Excel的必要程序
Unicode::Map为完全支持中文的字符集转换包
 
perldoc Spreadsheet::ParseExcel 介绍的很详细了
中文 excel 处理需要稍微多做一步
用 Spreadsheet::ParseExcel::FmtUnicode 指定 Unicode_Map 为 CP936

然后直接调用 Parse 方法就行了
返回值是一个关键数组 内容就是 excel 文件的内容

$oBook->{File} 是文件名
$oBook->{SheetCount} 是sheet个数
$oBook->{Worksheet}[0]->{Name} 是第一个 sheet 的名字
$oBook->{Worksheet}[1]->{MaxRow} 是第二个 sheet 的最大行
$oBook->{Worksheet}[2]->{Cells}[1][0]->{Val} 是第三个 sheet 的第二行第一列的值
$oBook->{Worksheet}[2]->{Cells}[1][0]->Value 是第三个 sheet 的第二行第一列的转化后的中文值

use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::FmtUnicode;

my $oExcel = new Spreadsheet::ParseExcel;
my $oCode = "CP936";
my $oFmtJ = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map => $oCode);
my $oBook = $oExcel->Parse($excelFile, $oFmtJ);

然后根据情况 循环sheet 行/row 列/column 处理就行了.

#==================================================

Demo

#!/usr/bin/perl -w

use strict;

use Spreadsheet::ParseExcel;

use Spreadsheet::ParseExcel::FmtUnicode;

use Encode qw /from_to/;

my $oExcel = new Spreadsheet::ParseExcel;

die "You must provide a filename to $0 to be parsed as an Excel file"

  unless @ARGV;


#set for charactor

my $oFmtC = Spreadsheet::ParseExcel::FmtUnicode->new( Unicode_Map => "CP936" );

my $oBook = $oExcel->Parse( $ARGV[0], $oFmtC );

my ( $iR, $iC, $oWkS, $oWkC );

print "FILE :",  $oBook->{File},       "\n";

print "COUNT :", $oBook->{SheetCount}, "\n";

print "AUTHOR:", $oBook->{Author},     "\n"

  if defined $oBook->{Author};

for ( my $iSheet = 0 ; $iSheet < $oBook->{SheetCount} ; $iSheet++ )

{

$oWkS = $oBook->{Worksheet}[$iSheet];

print "--------- SHEET:", $oWkS->{Name}, "\n";

for ( my $iR = $oWkS->{MinRow} ;

 defined $oWkS->{MaxRow} && $iR <= $oWkS->{MaxRow} ;

 $iR++ )

{

for ( my $iC = $oWkS->{MinCol} ;

 defined $oWkS->{MaxCol} && $iC <= $oWkS->{MaxCol} ;

 $iC++ )

{

$oWkC = $oWkS->{Cells}[$iR][$iC];

my $val = $oWkC->Value;

$val =~ s/\s+//ig;

from_to( $val, "CP936", "utf8" );


#print "( $iR , $iC ) =>", $oWkC->Value, "\n" if($oWkC);

print "( $iR , $iC ) =>", $val, "\n" if ($oWkC);

}

}

}


转载于:https://www.cnblogs.com/xiaoyixy/archive/2008/10/29/1322178.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值