Chinaunix首页 | 论坛 | 博客
  • 博客访问: 362943
  • 博文数量: 35
  • 博客积分: 2176
  • 博客等级: 大尉
  • 技术积分: 797
  • 用 户 组: 普通用户
  • 注册时间: 2006-08-13 14:03
文章分类

全部博文(35)

文章存档

2012年(9)

2009年(14)

2008年(12)

我的朋友

分类:

2009-06-03 13:49:28

最近接触一些需要csv,txt,excel文件之间的转换,根据一些网上搜索加上自己的改动,实现自己想要的结果为主要目的,代码的出处已经找不到了,还请见谅,以下主要是针对csv&excel 和txt&excel写的perl脚本。
主要用到的模块是:

Text::CSV
Spreadsheet::WriteExcel

Spreadsheet::ParseExcel

Spreadsheet::ParseExcel::FmtUnicode

Unicode::Map


可以支持中文,具体也没有要仔细说明的,直接看代码熟悉以上的模块吧!

txt&execl之间的转换:

execl2txt:

#!/usr/bin/perl
#===============================================================================
#
# FILE: excel2txt.pl
#
# USAGE: ./excel2txt.pl excel_filename txt_filename
#
# DESCRIPTION: Convert a Excel document to a text file
#
#===============================================================================


use strict;
use warnings;

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

unless($ARGV[0] && $ARGV[1])
{
        die "Please enter the filename of Excel document.
Usage : excel2txt.pl [Excel filename] [Text filename]
For example : excel2txt.pl input.xls output.txt"
;
}

# Chinese support

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

my $oExcel = new Spreadsheet::ParseExcel;
my $doc = $oExcel->Parse($ARGV[0],$oFmtJ) or die "File open error:$!\n";
my $outfile = $ARGV[1];


my $worksheet = $doc->{Worksheet}[0];
my $text;

# Get the excel data

for(my $row_num = $worksheet->{MinRow};$row_num <= $worksheet->{MaxRow};$row_num++)
{
        for(my $col_num = $worksheet->{MinCol};$col_num <= $worksheet->{MaxCol};$col_num++)
        {
                $text .= $worksheet->{Cells}[$row_num][$col_num]?$worksheet->{Cells}[$row_num][$col_num]->Value:"";

                if($col_num != $worksheet->{MaxCol})
                {
                        $text .= "\t"; # print tab

                }
                else
                {
                        $text .= "\r\n"; # print

                }
        }
}

# Write to file

open FH,">$outfile";
print FH $text;
close FH;
print "done!\n";



txt2excel:
#!/usr/bin/perl
#===============================================================================
#
# FILE: txt2excel.pl
#
# USAGE: ./txt2excel.pl [txt filename] [excel filename]
#
# DESCRIPTION: Convert text file to excel
#===============================================================================


use strict;
use warnings;

use Unicode::Map;
use Spreadsheet::WriteExcel;

unless($ARGV[0] && $ARGV[1])
{
        die " USAGE: ./txt2excel.pl [txt filename] [excel filename] \n ";
}

my $filename = $ARGV[1];
my $tmp_filename = $ARGV[0];

my $workbook = Spreadsheet::WriteExcel->new($filename);
my $worksheet = $workbook->add_worksheet();

# Chinese support

my $Map = new Unicode::Map("GB2312");

# Convert word to unicode

sub w2u
{
        my $word = shift;
        return $Map->to_unicode($word);
}

my $row = 0;
my $col = 0;

open FH,$tmp_filename or die"file open error.\n";
while(<FH>)
{
        chomp;
        $col = 0;
        s/\s+//g;
        my @array = split(";",$_);
        foreach my $value (@array)
        {
                $worksheet->write_unicode($row,$col,w2u($value));
                $col++;
        }
        $row++;
}
close FH;
print "done!";


接下来看看csv&excel之间的转换:

#!/usr/bin/perl -W
#
# File: excel2csv.pl
# License: GPL-2


use strict;
use warnings;

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


my $local_enc = "CP936";

unless($ARGV[0] && $ARGV[1])
{
        die "Please enter the filename of Excel document.
Usage : excel2csv.pl [Excel filename] [Csv filename]
For example : excel2csv.pl input.xls output.csv\n"
;
}

my $oFmtJ = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map => $local_enc);
my $excel = Spreadsheet::ParseExcel->new();
my $book = $excel->Parse($ARGV[0], $oFmtJ);

my $last_sheet = $book->{SheetCount} - 1;

my $filename = $ARGV[1];
open my $fh, ">", $filename
          or die "Can open $filename to write: $!\n";
for my $worksheet ( @{ $book->{Worksheet} }[ 0 .. $last_sheet ] ) {

     next
         if not defined $worksheet->{MaxRow}
         or not defined $worksheet->{MaxCol};



     my @row = $worksheet->{MinRow} .. $worksheet->{MaxRow};
     my @col = $worksheet->{MinCol} .. $worksheet->{MaxCol};

     for my $row ( @{ $worksheet->{Cells} }[ @row ] ) {
         my @cellvalue = map {
            $_ = $_->Value() if ref $_;
            $_ = '' if not defined $_;
            $_;
         } @$row[ @col ];
         print $fh join(";", @cellvalue), "\n";

    }
}
close $fh;


csv2excel用到的比较少,也就粗略了

#!/usr/bin/perl -w


use strict;
use Text::CSV;
use Spreadsheet::WriteExcel;

die("Usage: $0 [input filename(s)]\n") if (scalar @ARGV == 0);

my $xl = Spreadsheet::WriteExcel->new('output.xls');

foreach my $filename (@ARGV) {
    my $csv = Text::CSV->new;

    my $wsname = $filename;
    $wsname =~ s/.csv//g;
    $wsname =~ s/-/ /g;
    my $ws = $xl->add_worksheet($wsname);

    my $row = 1;
    open FH, $filename; while (<FH>) {
        $csv->parse($_);
        my @fields = $csv->fields;
        $ws->write("A$row", \@fields);
        $row++;
    }; close FH;
}


主要是做为备份,以免忘记丢失。
阅读(15080) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-08-04 10:34:49

楼主的代码写的实在是好,我有一个问题,就是在excel to csv 文件时候,excel中有多个sheet 又怎么处理呢,好像转换后,只有一个csv文件。 要是楼主有时间的话,写一个,读取(截取)excel文件的部分内容,有些不需要,直接生成csv文件。期待这样的代码~~呵呵,楼主谢谢啦。