سؤال

I do have this script that convert xls to xml, my excel file has to or three columns, the xmls format should be like this <testcase name="Test1"> but it prints <testcase name>test-1</testcase name>

per script is like this:

 my $file = 'myfile.xls';
 my @columns = ('testcase name', 'summary', 'preconditions');
 my $xls = XML::Excel->new({column_headings => \@columns});
 print $file;

 $xls->parse_doc($file);
 $xls->declare_xml({version => '1.0',
 encoding => 'UTF-8', standalone => 'yes'});
 $xls->print_xml('test.xml',
                    {
                    file_tag    => 'testcases',
                    parent_tag  => "testcase"
                    }
            );

thanks in advance..

هل كانت مفيدة؟

المحلول

I don't think XML::Excel can do what you require, it is a simple module and also quite old (2001). Here is a way to do it using Spreadsheet::ParseExcel (which XML::Excel uses) and XML::Writer. If you need to write to a file you can change the 'OUTPUT' option - see the docs.

use strict;
use warnings;

use Spreadsheet::ParseExcel;
use XML::Writer;

my @columns = ('name', 'summary', 'preconditions');
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('myfile.xls') or die $parser->error();
my $worksheet = $workbook->worksheet(0);
my ( $row_min, $row_max ) = $worksheet->row_range();
my @data;
for my $row ( $row_min .. $row_max ) {
    my %hash;
    for my $col (0 .. $#columns) {
        my $cell = $worksheet->get_cell( $row, $col );
        $hash{$columns[$col]} = $cell->value();
    }
    push(@data,\%hash)
}

my $writer = XML::Writer->new(OUTPUT => 'self', DATA_MODE => 1);
$writer->xmlDecl();
$writer->startTag('testcases');
for my $row (@data) {
    $writer->startTag('testcase', name => $row->{'name'});
    $writer->dataElement('summary', $row->{'summary'});
    $writer->dataElement('preconditions', $row->{'preconditions'});
    $writer->endTag('testcase');
}
$writer->endTag('testcases');
$writer->end;
print $writer->to_string;

Sample output:

<?xml version="1.0"?>
<testcases>
<testcase name="test1">
<summary>summary1</summary>
<preconditions>preconditions1</preconditions>
</testcase>
<testcase name="test2">
<summary>summary2</summary>
<preconditions>preconditions2</preconditions>
</testcase>
</testcases>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top