excel转化为lua配置(xls2lua)

去年瞎折腾的项目中使用到的配置都是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 ");

}

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 { ";

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

}

else

{

print"}, ";

}

}

print "} ";

}

脚本依赖:

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

git地址: https://github.com/liwanghong/xls2lua git地址: https://github.com/liwanghong/xls2lua

经验分享 程序员 微信小程序 职场和发展