去年瞎折腾的项目中使用到的配置都是excel写的,所以写了一个小的工具来将excel转为为lua。
工具代码(xls2lua.pl):
#!/usr/bin/perl
use Spreadsheet::Read;
use Getopt::Long;
my $xls_file;
my $opt;
my $id_col = 1;
GetOptions("x|xls=s" => \$xls_file,
"o|opt=s" => \$opt,
"c|col:i" => \$id_col)
or die ("Error param");
if ($opt ne "a" and $opt ne "h")
{
die ("Invalid opt\n");
}
my $book = ReadData("$xls_file");
my $sheet_num = $book->[0]{sheets};
my @titles;
for (my $sheet = 1; $sheet <= $sheet_num; $sheet = $sheet + 1)
{
my %content = %{$book->[$sheet]};
my $row = $content{maxrow};
my $col = $content{maxcol};
my @titles = {};
for (my $col_index = 1; $col_index <= $col; $col_index = $col_index + 1)
{
my $cell = cr2cell($col_index, 1);
my $value = $content{$cell};
push(@titles, $value);
}
print "$content{label} = $content{label} or {\n";
for(my $row_index = 2; $row_index <= $row; $row_index = $row_index + 1)
{
my $key_cell = cr2cell($id_col, $row_index);
my $key = $content{$key_cell};
if ($opt eq "a")
{
print " {\[\"$titles[$id_col]\"\] = \"$key\", ";
}
elsif ($opt eq "h")
{
print " [\"$key\"] = {";
}
for (my $col_index = $id_col + 1; $col_index <= $col; $col_index = $col_index + 1)
{
my $cell = cr2cell($col_index, $row_index);
my $value = $content{$cell};
$value =~ s/^\s+//;
$value =~ s/\s+$//;
print "\[\"$titles[$col_index]\"\] = \"$value\"";
if ($col_index != $col)
{
print ", ";
}
}
if ($row_index == $row)
{
print "}\n";
}
else
{
print"},\n";
}
}
print "}\n";
}
windows:
activePerl
linux / mac os:
default has perl
librarys:
linux/mac:
sudo cpan install Spreadsheet::Read
sudo cpan install Spreadsheet::XLSX
sudo cpan install Getopt::Long
windows:
可以直接用PPM下载上面三个模块
usage:
./xls2lua.pl --xls excel_file_path --opt [h|a] [--col index]
--xls(-x): excel 文件全路径
--opt(-o):
h means convert excel to hash table
a means convert excel to array
--col(-c):开始列索引,即从excel的第几页开始导出到lua,默认为1
注意:
该脚本只是将转化后的结果输出到屏幕,如果要保存成文件,用户可以自己修改脚本,或者使用如下方式:
linux/mac: ./xls2lua.pl -x excel_file -o a | tee file.lua
windows: xls2lua.pl -x excel_file -o -a > file.lua