Using LuaCOM to Control Microsoft Word and Microsoft Excel

Use a Lua script to generate Microsoft Word or Microsoft Excel documents with specified content without having to open the applications.

Ensure that you are using the Windows operating system and that Microsoft Word and/or Microsoft Excel is installed on the machine.
  1. Open the script editor.
  2. Create a new empty script.
  3. As an example, load one of the scripts below into the script editor.
  4. Run the script.
    -- MS WORD
    require "luacom"
    
    -- Open Word
    local msword = luacom.CreateObject("Word.Application")
    assert(msword, "Could not open MS Word")
    
    -- Initialise the document
    msword.Visible = true
    doc = msword.Documents:Add()
    
    -- Add content
    insertionPoint = doc.ActiveWindow.Selection
    insertionPoint.Style = "Heading 1"
    insertionPoint:TypeText( "Feko Says..." )
    insertionPoint:TypeParagraph()
    insertionPoint:TypeText( "Hello world!" )
    -- MS EXCEL
    require "luacom"
    
    -- Open Excel
    local excel = luacom.CreateObject("Excel.Application")
    assert(excel, "Could not open MS Excel")
    
    -- Initialise the worksheet
    excel.Visible = true
    workbook = excel.Workbooks:Add()
    worksheet = workbook.Worksheets:Add()
    
    -- Populate the data and display the contents of cell A3
    worksheet.Range( "A1", "A1" ).Value2 = [[hello]]
    worksheet.Range( "A2", "A2" ).Value2 = [[world]]
    worksheet.Range( "A3", "A3" ).Value2 = [[=CONCAT(A1," ",A2,"!!")]]
    feko.Form.Info( "Excel says...", worksheet.Range( "A3", "A3" ).Value2 )
    
    -- Change an input value and display A3 once again
    worksheet.Range( "A2", "A2" ).Value2 = [[everybody]]
    feko.Form.Info( "Excel says...", worksheet.Range( "A3", "A3" ).Value2 )