Skip to content

Commit

Permalink
[FIX] xlsx: preserve leading whitespace at export
Browse files Browse the repository at this point in the history
If a shared string has leading/trailing whitespace, it should have the
attribute `xml:space="preserve"` otherwise the whitespace is trimmed
in Excel.

closes #5377

Task: 4044862
Signed-off-by: Rémi Rahir (rar) <[email protected]>
Signed-off-by: Adrien Minne (adrm) <[email protected]>
  • Loading branch information
hokolomopo committed Jan 6, 2025
1 parent 3d0c96b commit 93eb716
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/xlsx/xlsx_writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,12 @@ function createSharedStrings(strings: string[]): XLSXExportFile {
["uniqueCount", strings.length],
];

const stringNodes = strings.map((string) => escapeXml/*xml*/ `<si><t>${string}</t></si>`);
const stringNodes = strings.map((string) => {
if (string.trim() !== string) {
return escapeXml/*xml*/ `<si><t xml:space="preserve">${string}</t></si>`;
}
return escapeXml/*xml*/ `<si><t>${string}</t></si>`;
});

const xml = escapeXml/*xml*/ `
<sst ${formatAttributes(namespaces)}>
Expand Down
14 changes: 14 additions & 0 deletions tests/xlsx/xlsx_export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,20 @@ describe("Test XLSX export", () => {
expect(styles[1].querySelector("alignment")!.getAttribute("wrapText")).toBe("1");
});

test("Leading and trailing whitespace in strings are preserved", async () => {
const model = new Model();
setCellContent(model, "A1", " Multiline with\n leading and trailing spaces\n ");

const exportedXlsx = await exportPrettifiedXlsx(model);
const sharedStrings = parseXML(
exportedXlsx.files.find((f) => f["contentType"] === "sharedStrings")!["content"]
);

const string = sharedStrings.querySelector("si t")!;
expect(string.getAttribute("xml:space")).toBe("preserve");
expect(string.textContent).toBe(" Multiline with\n leading and trailing spaces\n ");
});

describe("formulas", () => {
beforeAll(() => {
functionRegistry.add("NOW", {
Expand Down

0 comments on commit 93eb716

Please sign in to comment.