用于将.xls中的内容转换为.xml的perl代码

时间:2013-07-01 09:59:00

标签: xml perl xslt

任何人帮我编写一个perl脚本,用于从.xls / .csv文件中创建.xml ....

我正在尝试以下代码......并且它无法正常运行...

#!/usr/bin/perl

use strict;
use warnings;
use Spreadsheet::ParseExcel;
use XML::Writer ();
use XML::Writer::String ();
use IO::File;
use File::Find;

print"Enter1";

my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('C:\Users\uidw3321\Desktop\one.xls');

if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}
my $xml_doc = XML::Writer::String->new();
my $xml_file = new IO::File(">D:\\tmp\\bmw.xml");
my $xml_doc_writer = new XML::Writer(OUTPUT =>  $xml_file);             

for my $worksheet ( $workbook->worksheets() ) {

    my ( $row_min, $row_max ) = $worksheet->row_range();
    my ( $col_min, $col_max ) = $worksheet->col_range();

    my %headers = ();
    for my $row ( $row_min .. $row_max ) {
        for my $col ( $col_min .. $col_max ) {
    my $cell = $worksheet->get_cell( $row, $col );
            if ($row == 0) {
                $headers{$col} = $cell->unformatted();
            } else {
                $xml_doc_writer->dataElement($headers{$col},$cell->unformatted());
            }
        }
    }

}
$xml_doc_writer->end(); 
$xml_file->close();

请帮忙

1 个答案:

答案 0 :(得分:1)

您的代码抛出错误:“在关闭文档元素后尝试插入开始标记”。 要解决此问题,只需使用某个标记启动XML内容:

$xml_doc_writer->startTag("someTag");

并以

结束
$xml_doc_writer->endTag();

总结您的工作代码应为:

#!/usr/bin/perl

use strict;
use warnings;
use Spreadsheet::ParseExcel;
use XML::Writer ();
use XML::Writer::String ();
use IO::File;
use File::Find;

print"Enter1";

my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('C:\Users\uidw3321\Desktop\one.xls');

if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}
my $xml_doc = XML::Writer::String->new();
my $xml_file = new IO::File(">D:\\tmp\\bmw.xml");
my $xml_doc_writer = new XML::Writer(OUTPUT =>  $xml_file);             

$xml_doc_writer->startTag("someTag");
for my $worksheet ( $workbook->worksheets() ) {

    my ( $row_min, $row_max ) = $worksheet->row_range();
    my ( $col_min, $col_max ) = $worksheet->col_range();

    my %headers = ();
    for my $row ( $row_min .. $row_max ) {
        for my $col ( $col_min .. $col_max ) {
    my $cell = $worksheet->get_cell( $row, $col );
            if ($row == 0) {
                $headers{$col} = $cell->unformatted();
            } else {
                $xml_doc_writer->dataElement($headers{$col},$cell->unformatted());
            }
        }
    }

}

$xml_doc_writer->endTag();
$xml_doc_writer->end(); 
$xml_file->close();

我希望它会有所帮助,干杯!