from http://sunxiunan.com/?p=1258
為了方便起見,最好安裝lua for windows,裡面已經包含了很多有用的第三方模組。
require(’luacom’) — luacom
ie = luacom.CreateObject(”InternetExplorer.Application”)
ie:Navigate2(”http://sunxiunan.com”)
ie.Visible = true
使用lua調用excel,然後往cell裡面填一些資料。
require(’luacom’) — luacom
– Excelの起動
excel = luacom.CreateObject(”Excel.Application”)
excel.Visible = true — 可視狀態に
– ワークブックを追加
local book = excel.Workbooks:Add()
local sheet = book.Worksheets(1)
– 適當な値を100個書き込む
for row=1,100 do
sheet.Cells(row, 1).Value2 = math.floor(math.random() * 20)
end
稍微複雜一些的代碼
require “luacom”
excel = luacom.CreateObject(”Excel.Application”)
local book = excel.Workbooks:Add()
local sheet = book.Worksheets(1)
excel.Visible = true
– 適當な値を書き込む
for row=1,30 do
for col=1,30 do
sheet.Cells(row, col).Value2 = math.floor(math.random() * 100)
end
end
– 値を調べて50以上のものを黃色でマークする
local range = sheet:Range(”A1″)
for row=1,30 do
for col=1,30 do
local v = sheet.Cells(row, col).Value2
if v > 50 then
local cell = range:Offset(row-1, col-1)
cell:Select()
excel.Selection.Interior.Color = 65535
end
end
end
excel.DisplayAlerts = false — 終了確認を出さないようにする
excel:Quit()
excel = nil
如果想給excel加個圖表該怎麼做?
require “luacom”
excel = luacom.CreateObject(”Excel.Application”)
local book = excel.Workbooks:Add()
local sheet = book.Worksheets(1)
excel.Visible = true
for row=1,30 do
sheet.Cells(row, 1).Value2 = math.floor(math.random() * 100)
end
local chart = excel.Charts:Add()
chart.ChartType = 4 — xlLine
local range = sheet:Range(”A1:A30″)
chart:SetSourceData(range)
如果想調用windows api,可以用下面的代碼
require “alien”
MessageBox = alien.User32.MessageBoxA
MessageBox:types{ret = ‘long’, abi = ’stdcall’, ‘long’, ’string’,
’string’, ‘long’ }
MessageBox(0, “title for test”, “LUA call windows api”, 0)
如何?回呼函數呢?下面的例子展示了回調。
require ‘alien’
–聲明了兩個函數EnumWindows和GetClassName
EnumWindows = alien.user32.EnumWindows
EnumWindows:types {”callback”, “pointer”, abi=”stdcall”}
GetClassName = alien.user32.GetClassNameA
GetClassName:types {”long”, “pointer”, “int”, abi=”stdcall” }
local buf = alien.buffer(512)
– 會被EnumWindows反覆調用,傳入windows的handle
local function enum_func(hwnd, p)
GetClassName(hwnd, buf, 511)
print (hwnd..”:”..tostring(buf))
return 1
end
local callback_func = alien.callback(
enum_func,
{”int”, “pointer”, abi=”stdcall”})
EnumWindows(callback_func, nil)
其中函數原型是
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);
int GetClassName(HWND hWnd, LPTSTR lpClassName, int nMaxCount);
其中EnumWindows第一個參數的原型為,這個函數是客戶調用時候傳入,EnumWindows用它返回
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
其他複雜的使用方法可以參考alien的文檔。
這些代碼都來自www.hakkaku.net/articles/20090615-459