Chinaunix

标题: perl 中文乱码的问题 [打印本页]

作者: bblxl2012    时间: 2014-06-24 14:53
标题: perl 中文乱码的问题
请教各位大神,如下代码读取excel的时候中文是乱码,该如何解决,请赐教,谢谢。

#!/usr/bin/perl

use Spreadsheet::Read;
use Spreadsheet::Xlsx;


my $fh = shift;

my $book = ReadData( $fh ) or die "Cannot read file";

my $sheet = $book->[1];

my $count = $sheet->{maxrow};

print ("The count is: $count\n");

foreach $line ( 1..$sheet->{maxrow} ) {

        my $cellE5  = $sheet->{"E$line"};

        my $cellF6  = $sheet->{"F$line"};

        print ("The result is: $cellE5   $cellF6 \n");

}
作者: huang6894    时间: 2014-06-24 16:52
use Encode(qw(decode));
作者: bblxl2012    时间: 2014-06-24 17:13
huang6894 发表于 2014-06-24 16:52
use Encode(qw(decode));


不管用,谢谢。还有其他办法吗?
作者: huang6894    时间: 2014-06-24 17:28
回复 3# bblxl2012


    你怎么用的?
作者: huang6894    时间: 2014-06-24 17:37
本帖最后由 huang6894 于 2014-06-24 17:38 编辑
  1. use Encode;
  2. our $local_enc = 'cp936';
  3. sub decode_cell($){
  4.   my $cell = shift;
  5.         if (!$cell){
  6.                 return '';
  7.         }
  8.                 if ($cell->{Type} eq 'Text' && defined($cell->{Code})) {
  9.                         if ($cell->{Code} eq 'ucs2') {
  10.                                 $cell->{Val} = decode('UTF16-BE', $cell->{Val});
  11.                         }elsif ($cell->{Code} eq '_native_') {
  12.                                 $cell->{Val} = decode($local_enc, $cell->{Val});
  13.                         }
  14.                 }
  15.                 elsif ($cell->{Type} eq 'Date') {
  16.                 }
  17.                 elsif ($cell->{Type} eq 'Number') {
  18.                 }
  19.                 return $cell->{Val};
  20. }
  21. foreach $i ($sheet->{MinRow}..$sheet->{MaxRow}) {
  22.                 $sheet->{MaxCol} ||= $sheet->{MinCol};
  23.                 $line = join("\t", map {encode('utf8', decode_cell($sheet->{Cells}[$i][$_]))} ($sheet->{MinCol}..$sheet->{MaxCol}));
  24.                 if ($line =~ m/^\t*$/) {
  25.                         $line = '';
  26.                                 }
  27.                 print $line."\n";
  28.                         }
  29.         }
  30. }
复制代码
一个参考
作者: stanley_tam    时间: 2014-06-24 20:54
看过这篇文章没有{:3_193:}
  1. http://bbs.chinaunix.net/thread-1857627-1-1.html
复制代码

作者: bblxl2012    时间: 2014-06-25 12:12
stanley_tam 发表于 2014-06-24 20:54
看过这篇文章没有


非常感谢,解决了。
加了如下3行即可。

use utf8;
use open ':encoding(gbk)', ':std';
use open ':encoding(utf';
作者: mcshell    时间: 2014-06-25 13:42
看这个吧
http://bbs.chinaunix.net/thread-1626493-1-1.html
作者: hmlijg    时间: 2014-06-25 14:56
把pl用记事本另存为,可以选择编码类型,选择ANSI试试




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2