[英]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.