如何在Lua中读取和解析excel文件?

时间:2012-06-21 13:14:19

标签: excel parsing lua corona xls

我想读取一个xls文件,然后解析它。我怎么能用Lua做到这一点?感谢。

1 个答案:

答案 0 :(得分:1)

这不是重复,因为他实际上只是想从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并浏览正确的连接字符串。