Julia Excel Object

Viewed 636
1 Answers

There are two options:

  1. Use a Julia native library (XLSX.jl) <== RECOMMENDED
  2. Use some of available Python libraries via PyCall.jl (works as charm as well) - among those options VBA-like command option is available as well - see code at the end of this post

Ad.1.

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", "")
 Cell(A4, "", "", "0.15112461473849814", "")  Cell(B4, "", "", "0.9088105399888486", "")
 Cell(A5, "", "", "0.38606711950516326", "")  Cell(B5, "", "", "0.274487313772527", "")
 Cell(A6, "", "", "0.4390332370925689", "")   Cell(B6, "", "", "0.04038483579623442", "")

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"))

Perhaps usually you will prefer a high-level DataFrames-oriented API:

using XLSX
using DataFrames
df1 = DataFrame(a=1:3, b=6:8);
df2 = DataFrame(x1=1:3, x2=string.('A':'C'));


XLSX.writetable("myexcel.xlsx",
    MySheetName1=(collect(eachcol(df1)), names(df2)),
    MySheetName2=(collect(eachcol(df2)), names(df2)))

Ad.2.

Start by installing openpyxl:

using Conda
Conda.add("openpyxl")

And then any Python example will work, e.g.:

using PyCall
xl = pyimport("openpyxl")

wb = xl.Workbook();
ws = wb.active

ws["A1"] = "hello world"

wb.save("yetanother.xlsx")

Last but not least, you can automate Excel via ActiveX. For most case scenarios I do not recommend it (speed, non cross-platform, requires Office installed, requires desktop environment etc.) but here it is:

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()
Related