1

任何人都可以帮助我编写一个 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();

请帮忙

4

1 回答 1

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();

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

于 2013-09-19T19:18:22.800 回答