2014-01-22 133 views
1

我確實有這個腳本轉換XLS爲XML,我的excel文件有三個列,在個XML格式應該是這樣的<testcase name="Test1"> but it prints <testcase name>test-1</testcase name>perl的轉換XLS爲xml

每個腳本是這樣的:

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" 
        } 
      ); 

在此先感謝..

回答

1

我不認爲XML :: Excel可以做你需要什麼,這是一個簡單的模塊,也很舊的(2001)。這是一種使用Spreadsheet::ParseExcel(XML :: Excel使用)和XML::Writer的方法。如果您需要寫入文件,您可以更改'OUTPUT'選項 - 請參閱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; 

輸出示例:

<?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> 
+0

感謝,但該輸出不是我想要的,我拿到的是:< records> 測試2,我想是這樣的<測試用例NAME =「測試1」> – user2912312

+0

@ user2912312這沒有任何意義,我不輸出在我的代碼被稱爲「記錄」,「記錄」或「測試1」的任何標記。我已更新以顯示示例輸出。 – tangent

+0

@ user2912312聽起來你仍然在使用XML :: Excel,因爲'記錄'和'記錄'是該模塊輸出的默認標記。 – tangent