[英]How to read and parse excel files in Lua?
我想读取一个xls文件,然后解析它。 我如何用Lua做到这一点? 谢谢。
这不是重复的,因为他实际上只是想从excel文件中读取并解析数据-而不是操作excel对象。
每当必须这样做时,我都会使用ADO使用luasql 。 在最基本的级别上,如果您知道查询的每一行中将包含多少个字段,则将使用这种方法来打开数据库连接并从中读取excel数据。
function rows(connection, sql_stmt)
local cursor = assert(connection:execute(sql_stmt))
return function()
return cursor:fetch()
end
end
local fpath = "path/to/file.xlxs"
local constr = "Provider=Microsoft.ACE.OLEDB.12.0;"..
"Data Source=\""..fpath.."\";"..
"Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
local env = assert(luasql.ado())
local con = assert(env:connect(constr))
-- the name of the worksheet needs to be surrounded by brackets, and end
-- with a '$' sign.
local query = "SELECT * FROM \[name_of_worksheet$\]"
-- you can do this if you know how many fields you get back specifically.
for field1, field2, field3, ... in rows(con, query) do
-- handle any parsing of data from a row, here.
end
con:close()
env:close()
如果您不知道要返回多少字段,可以执行以下操作:
local fpath = "path/to/file.xlxs"
local constr = "Provider=Microsoft.ACE.OLEDB.12.0;"..
"Data Source=\""..fpath.."\";"..
"Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
local env = assert(luasql.ado())
local con = assert(env:connect(constr))
-- the name of the worksheet needs to be surrounded by brackets, and end
-- with a '$' sign.
local query = "SELECT * FROM \[name_of_worksheet$\]"
-- if you didn't know how many fields you might get back per row, i
-- believe you can do this to iterate over each row...
local cursor = con:execute(query)
local t = {}
local results = cursor:fetch(t)
while results ~= nil do
for k,v in pairs(results) do
-- check each field in the row here
end
results = con:fetch(t)
end
cursor:close()
con:close()
env:close()
完成操作后,请确保关闭它们的游标/连接/环境。 此外,您还需要验证上面的连接字符串是否适用于您的excel版本。 确定所需哪个连接字符串的最简单方法是访问www.connectionstrings.com,浏览正确的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.