2

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

4

1 回答 1

2

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

于 2012-06-21T14:20:18.687 回答