XLSX.jl icon indicating copy to clipboard operation
XLSX.jl copied to clipboard

Writing to a cell in a template overwrites existing formats

Open TimG1964 opened this issue 11 months ago • 1 comments

If I open an xlsx file as a template, populate some cells and then save to a new file, the formatting in the template gets overwritten with the default style. I think it should retain the style in the template. Here is a simple example (using the CustomXML.xlsx file from the test data set).

using XLSX

xf = XLSX.open_xlsx_template(raw"XLSX.jl\data\customXml.xlsx")

sh = xf["Mock-up"]

sh["B2"] = "Hello Me"
sh["H2"] = "Hello Me"
sh["M2"] = "Hello Me"

XLSX.writexlsx("test.xlsx", xf, overwrite=true)

Template:

Image

After writing new values into B2, H2 and M2 with current code:

Image

With simple fix

Image

The fix is to change one of the setdata!() functions in write.jl (line 369):

function setdata!(ws::Worksheet, ref::CellRef, val::CellValueType) # use existing cell format if it exists
    c = getcell(ws, ref)
    if c isa EmptyCell || c.style == ""
        return setdata!(ws, ref, CellValue(ws, val))
    else
        existing_style = CellDataFormat(parse(Int, getcell(ws, ref).style))
        return setdata!(ws, ref, CellValue(val, existing_style))
    end
end
# setdata!(ws::Worksheet, ref::CellRef, val::CellValueType) = setdata!(ws, ref, CellValue(ws, val))

I'd like to make a small PR for this but I can't at present due to my own issues with github inexperience. #280 is blocking my fork of this repo at present - I've done something silly with branches...!)

My suggested code passes all tests locally and does not depend on #280.

TimG1964 avatar Feb 02 '25 13:02 TimG1964