2

I'm programing in Julia and trying to create an excel file with multiple sheets for saving some data. The problem is that the function XLSX.openxlsx() only creates excels with one sheet. I'm trying to run the following code.

XLSX.openxlsx("test_file.xlsx", mode="w") do xf
    sheet = xf[1]
    XLSX.rename!("first")
    sheet["A1"] = "A"
    sheet = xf[2]
    XLSX.rename!("second")
    sheet["A1"] = "B"
    sheet = xf[3]
    XLSX.rename!("third")
    sheet["A1"] = "C"
end

Does anyone know how to create excel files with multiple sheets? or maybe create new sheets in an existing file?

2 Answers 2

2

XLSX.addsheet! is what you're looking for.

XLSX.openxlsx("test_file.xlsx", mode="w") do xf
    XLSX.rename!(xf[1], "first")

    for sheetname in ["second", "third", "fourth"]
      XLSX.addsheet!(xf, sheetname)
    end

    xf[1]["A1"] = "A"
    xf[2]["A1"] = "B"
    xf[3]["A1"] = "C"

    # ...
end

Sign up to request clarification or add additional context in comments.

Comments

2

writetable accepts several worksheets as keyword arguments. Hence, I usually use a one-liner to export all data frames to an Excel file. I also definitely recommend to create a DataFrame, manipulate it and finally save to Excel as the DataFrames API is obviously more convenient than XLSX API for data manipulation.

See the code below:

using DataFrames, XLSX
df1 = DataFrame(a=1:5, b=string.("Hello",1:5), c=6.5:10.5)
df2 = DataFrame(a=1:5, d=[11,22,33,missing,missing] )

XLSX.writetable("dfs.xlsx", overwrite=true, 
    WORKSHEET_A=(collect(DataFrames.eachcol(df1)), DataFrames.names(df1)),
    WORKSHEET_B=(collect(DataFrames.eachcol(df2)), DataFrames.names(df2)),
    #add more data frames when needed   
)

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.