【问题标题】:Using Lua for working with excel使用 Lua 处理 excel
【发布时间】:2017-05-15 23:43:16
【问题描述】:

我计划学习 Lua 以满足我的桌面脚本需求。我想知道是否有任何可用的文档,以及标准库中是否有所有需要的东西。

【问题讨论】:

    标签: excel lua


    【解决方案1】:

    您应该查看 Lua for Windows——Windows 上 Lua 脚本语言的“包含电池的环境”

    http://luaforwindows.luaforge.net/

    它包括 LuaCOM 库,您可以从中访问 Excel COM 对象。

    尝试查看 LuaCOM 文档,其中有一些 Excel 示例:

    http://www.tecgraf.puc-rio.br/~rcerq/luacom/pub/1.3/luacom-htmldoc/

    我只将它用于非常简单的事情。这是一个让您入门的示例:

    -- test.lua
    require('luacom')
    excel = luacom.CreateObject("Excel.Application")
    excel.Visible = true
    wb = excel.Workbooks:Add()
    ws = wb.Worksheets(1)
    
    for i=1, 20 do
        ws.Cells(i,1).Value2 = i
    end
    

    【讨论】:

    • 感谢 uroc 的快速回复。如果可能的话,请让我知道任何初学者教程或至少一些通过 Lua 使用 COM 编程的示例代码。 :)
    【解决方案2】:

    lua 使用 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
      for col=1, 30 do
        sheet.Cells(row, col).Value2 = math.floor(math.random() * 100)
      end
    end
    
    
    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 
    

    另一个例子,可以添加图表。

    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) 
    

    【讨论】:

    • 一个快速建议:如果您将代码片段格式化为代码(使用小“101 010”按钮),代码片段看起来会更好。
    猜你喜欢
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多