Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you run a .jl file from an excel macro

Tags:

excel

vba

julia

I am trying to execute Julia code that outputs information into a text file. I need to give users who do not know Julia accurate answers. Can I build an excel macro that runs that .Jl on my computer?

Thanks in advance,

like image 214
Dah la la Avatar asked Dec 28 '25 19:12

Dah la la


1 Answers

There was a commercial Julia Excel add-in JuliaInXL but most likely it has died.

What you can do is to manipulate programmatically Excel from Julia.

XLSX.jl

Writing a spreadsheet

using XLSX
using Dates
XLSX.openxlsx("smyample.xlsx", mode="w") do xf
    sheet = xf[1]
    XLSX.rename!(sheet, "NewSheetName")
    sheet["A1"] = "Data generated on:"
    sheet["B1"] =  Dates.now()
    dat = rand(4, 5)
    for i in 1:size(dat,1), j in 1:size(dat,2)
        XLSX.setdata!(sheet, XLSX.CellRef(2+i, j), dat[i,j])
    end
end

Reading a spreadsheet:

julia> wb = XLSX.readxlsx("mysample.xlsx")
XLSXFile("sample2.xlsx") containing 1 Worksheet
            sheetname size          range
-------------------------------------------------
         NewSheetName 6x5           A1:E6

Let's get first two columns:

julia> XLSX.getcellrange(ws, ws.dimension)[:,1:2]
6×2 Array{XLSX.AbstractCell,2}:
 Cell(A1, "s", "", "0", "")                   Cell(B1, "", "1", "43995.77937614583", "")
 EmptyCell(A2)                                EmptyCell(B2)
 Cell(A3, "", "", "0.7723129181734945", "")   Cell(B3, "", "", "0.9539233196840988", "")
...

a Cell object has a field value so you can further process it.

You can also simply ask for any cell as well:

julia> ws["A1"], ws["B1"]
("Data generated on:", DateTime("2020-06-13T18:42:18"))

ActiveX automation - this will enable calling an Excel macro from Julia

In this way any operation on a running excel spreadsheet can be performed - you are just robotizing MS Excel.

using Conda
Conda.add("pywin32")

using PyCall
pw = pyimport("win32com")
pwc = pyimport("win32com.client")
import win32com.client

xlApp = pwc.Dispatch("Excel.Application")
xlApp.Visible=1
workBook = xlApp.Workbooks.Open("C:\\temp\\MyTest.xlsx")
workBook.ActiveSheet.Cells(1, 1).Value = "hello world"
workBook.Close(SaveChanges=1) 
xlApp.Quit()
like image 81
Przemyslaw Szufel Avatar answered Dec 30 '25 22:12

Przemyslaw Szufel