Preserve QExcell print areas in XLSX

This commit is contained in:
Курнат Андрей
2026-06-01 19:48:24 +03:00
parent f22c7af88b
commit 7337dbf5cd
5 changed files with 163 additions and 7 deletions
+41
View File
@@ -17,6 +17,7 @@ import {
chartDataPoints,
chartXmlToSheetChart,
workbookActiveSheetId,
workbookPrintAreas,
workbookRelationshipTargets,
workbookSheetRefs,
worksheetXmlToAutoFilter,
@@ -576,6 +577,46 @@ describe("excellOffice OOXML helpers", () => {
expect(imported.activeSheet).toBe("sheet-2");
});
it("сохраняет и импортирует область печати XLSX через definedName _xlnm.Print_Area", async () => {
expect(
workbookPrintAreas(
{
workbook: {
definedNames: {
definedName: [
{ name: "_xlnm.Print_Area", localSheetId: "0", "#text": "'Отчет'!$D$20:$A$1" },
{ name: "_xlnm.Print_Area", localSheetId: "1", "#text": "'Архив'!$B$2:$C$4,'Архив'!$E$1:$E$3" }
]
}
}
},
[
{ id: "sheet-1", name: "Отчет" },
{ id: "sheet-2", name: "Архив" }
]
)
).toEqual({ "sheet-1": "A1:D20", "sheet-2": "B2:C4,E1:E3" });
const blob = await exportXlsxBlob({
id: "book-1",
title: "Область печати.xlsx",
updatedAt: "2026-06-01T00:00:00.000Z",
activeSheet: "sheet-1",
sheets: [
{ id: "sheet-1", name: "Отчет", printArea: "D20:A1", cells: { A1: "Начало", D20: "Итог" } },
{ id: "sheet-2", name: "Архив", printArea: "B2:C4,E1:E3", cells: { B2: "Архив" } }
]
});
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
const workbookXml = await zip.file("xl/workbook.xml")?.async("string");
const imported = await importXlsxFile(new File([blob], "Область печати.xlsx", { type: blob.type }));
expect(workbookXml).toContain('<definedNames><definedName name="_xlnm.Print_Area" localSheetId="0">\'Отчет\'!$A$1:$D$20</definedName>');
expect(workbookXml).toContain('<definedName name="_xlnm.Print_Area" localSheetId="1">\'Архив\'!$B$2:$C$4,\'Архив\'!$E$1:$E$3</definedName></definedNames>');
expect(imported.sheets[0].printArea).toBe("A1:D20");
expect(imported.sheets[1].printArea).toBe("B2:C4,E1:E3");
});
it("сохраняет и импортирует скрытые листы XLSX через sheet state", async () => {
const blob = await exportXlsxBlob({
id: "book-1",
+95 -5
View File
@@ -16,6 +16,7 @@ export interface ImportedExcellWorkbook {
rowHeights?: Record<string, number>;
showGridLines?: boolean;
zoomScale?: number;
printArea?: string;
cells: Record<string, string>;
mergedCells?: MergedCellRange[];
hyperlinks?: Record<string, string>;
@@ -70,6 +71,7 @@ interface ParsedSheet {
rowHeights?: Record<string, number>;
showGridLines?: boolean;
zoomScale?: number;
printArea?: string;
cells: Record<string, string>;
mergedCells?: MergedCellRange[];
hyperlinks?: Record<string, string>;
@@ -210,12 +212,22 @@ export async function importXlsxFile(file: File): Promise<ImportedExcellWorkbook
const themeColors = await readOptionalWorkbookThemeColors(zip, parser);
const styleTable = xlsxStylesXmlToCellFormatTable(await readOptionalWorkbookStyles(zip, parser), themeColors);
const sheetRefs = workbookSheetRefs(workbookXml);
const printAreas = workbookPrintAreas(workbookXml, sheetRefs);
const relationshipTargets = workbookRelationshipTargets(relationshipsXml);
const sheets = await Promise.all(
sheetRefs.map(async (sheet, index) => {
const target = relationshipTargets[sheet.relationshipId];
if (!target) {
return { id: sheet.id, name: sheet.name, cells: {}, mergedCells: [], hyperlinks: {}, cellFormats: {}, charts: [] };
return {
id: sheet.id,
name: sheet.name,
...(printAreas[sheet.id] ? { printArea: printAreas[sheet.id] } : {}),
cells: {},
mergedCells: [],
hyperlinks: {},
cellFormats: {},
charts: []
};
}
const sheetPath = resolveWorkbookTarget(target);
@@ -223,7 +235,7 @@ export async function importXlsxFile(file: File): Promise<ImportedExcellWorkbook
const sheetRelationshipsXml = await readOptionalSheetRelationships(zip, parser, sheetPath);
const parsedSheet = parsedWorksheetToSheet(sheetXml, sheet, index, sharedStrings, sheetRelationshipsXml, styleTable, themeColors);
const charts = await worksheetXmlToCharts(zip, parser, sheetXml, sheetRelationshipsXml, sheetPath, parsedSheet.name);
return { ...parsedSheet, charts };
return { ...parsedSheet, ...(printAreas[sheet.id] ? { printArea: printAreas[sheet.id] } : {}), charts };
})
);
const activeSheet = workbookActiveSheetId(workbookXml, sheets);
@@ -253,7 +265,8 @@ export async function exportXlsxBlob(workbook: Workbook): Promise<Blob> {
buildWorkbookXml(
sheets.map((sheet, index) => ({
name: sheet.name.trim() || `Лист ${index + 1}`,
...(sheet.visibility ? { visibility: sheet.visibility } : {})
...(sheet.visibility ? { visibility: sheet.visibility } : {}),
...(sheet.printArea ? { printArea: sheet.printArea } : {})
})),
activeSheetIndex
)
@@ -901,6 +914,28 @@ export function workbookActiveSheetId(workbookXml: unknown, sheets: Array<{ id:
return sheets[activeTab]?.id ?? "";
}
export function workbookPrintAreas(workbookXml: unknown, sheets: Array<{ id: string; name: string }>): Record<string, string> {
const workbook = childRecord(workbookXml, "workbook");
const definedNames = childRecord(workbook, "definedNames");
return toArray(definedNames.definedName).reduce<Record<string, string>>((areas, definedName) => {
const record = asRecord(definedName);
const name = String(record.name ?? record["@_name"] ?? "").trim();
const localSheetId = Number.parseInt(String(record.localSheetId ?? record["@_localSheetId"] ?? ""), 10);
const sheet = Number.isInteger(localSheetId) && localSheetId >= 0 ? sheets[localSheetId] : undefined;
if (name !== "_xlnm.Print_Area" || !sheet) {
return areas;
}
const printArea = printAreaFromDefinedName(xmlNodeText(record), sheet.name);
if (printArea) {
areas[sheet.id] = printArea;
}
return areas;
}, {});
}
export function workbookRelationshipTargets(relationshipsXml: unknown) {
const relationships = childRecord(relationshipsXml, "Relationships");
const targets: Record<string, string> = {};
@@ -954,7 +989,7 @@ function buildRootRelationshipsXml() {
);
}
function buildWorkbookXml(sheets: Array<{ name: string; visibility?: WorkbookSheetRef["visibility"] }>, activeSheetIndex = 0) {
function buildWorkbookXml(sheets: Array<{ name: string; visibility?: WorkbookSheetRef["visibility"]; printArea?: string }>, activeSheetIndex = 0) {
const activeTab = Math.min(Math.max(0, activeSheetIndex), Math.max(0, sheets.length - 1));
const bookViews = `<bookViews><workbookView activeTab="${activeTab}"/></bookViews>`;
const sheetXml = sheets
@@ -963,12 +998,27 @@ function buildWorkbookXml(sheets: Array<{ name: string; visibility?: WorkbookShe
return `<sheet name="${escapeXmlAttribute(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"${visibility}/>`;
})
.join("");
const definedNames = buildWorkbookDefinedNamesXml(sheets);
return xmlDeclaration(
`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${bookViews}<sheets>${sheetXml}</sheets></workbook>`
`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${bookViews}<sheets>${sheetXml}</sheets>${definedNames}</workbook>`
);
}
function buildWorkbookDefinedNamesXml(sheets: Array<{ name: string; printArea?: string }>) {
const definedNames = sheets
.map((sheet, index) => {
const printArea = normalizePrintArea(sheet.printArea ?? "");
return printArea
? `<definedName name="_xlnm.Print_Area" localSheetId="${index}">${escapeXmlText(printAreaFormula(sheet.name, printArea))}</definedName>`
: "";
})
.filter(Boolean)
.join("");
return definedNames ? `<definedNames>${definedNames}</definedNames>` : "";
}
function buildWorkbookRelationshipsXml(sheetCount: number) {
const sheetRelationships = Array.from({ length: sheetCount }, (_, index) => {
return `<Relationship Id="rId${index + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${index + 1}.xml"/>`;
@@ -1122,6 +1172,13 @@ function chartRangeFormula(sheetName: string, range: string) {
return `${quotedSheetName(sheetName)}!${absoluteChartRange(range)}`;
}
function printAreaFormula(sheetName: string, printArea: string) {
return normalizePrintArea(printArea)
.split(",")
.map((range) => `${quotedSheetName(sheetName)}!${absolutePrintAreaRange(range)}`)
.join(",");
}
function quotedSheetName(sheetName: string) {
return `'${sheetName.replace(/'/g, "''")}'`;
}
@@ -1132,6 +1189,12 @@ function absoluteChartRange(range: string) {
return `${absoluteCellAddress(start)}:${absoluteCellAddress(end)}`;
}
function absolutePrintAreaRange(range: string) {
const normalized = normalizeCellRange(range);
const [start, end = start] = normalized.split(":");
return `${absoluteCellAddress(start)}:${absoluteCellAddress(end)}`;
}
function absoluteCellAddress(address: string) {
const column = address.match(/^[A-Z]+/i)?.[0]?.toUpperCase() ?? "A";
const row = address.match(/[1-9][0-9]*$/)?.[0] ?? "1";
@@ -1869,6 +1932,33 @@ function normalizeCellRange(range: string) {
return normalized ? `${normalized.start}:${normalized.end}` : normalizedStart;
}
function normalizePrintArea(value: string) {
const ranges = value
.split(",")
.map((range) => normalizeCellRange(range))
.filter(Boolean);
return [...new Set(ranges)].join(",");
}
function printAreaFromDefinedName(value: string, sheetName: string) {
const ranges = value
.split(",")
.map((range) => printAreaRangeFromFormula(range, sheetName))
.filter(Boolean);
return [...new Set(ranges)].join(",");
}
function printAreaRangeFromFormula(formula: string, sheetName: string) {
const raw = formula.trim();
const separatorIndex = raw.lastIndexOf("!");
const rawSheetName = separatorIndex >= 0 ? raw.slice(0, separatorIndex).replace(/^'|'$/g, "").replace(/''/g, "'") : "";
if (rawSheetName && rawSheetName !== sheetName) {
return "";
}
return normalizeCellRange((separatorIndex >= 0 ? raw.slice(separatorIndex + 1) : raw).replace(/\$/g, ""));
}
function uniqueNumbers(values: number[]) {
return [...new Set(values)].sort((first, second) => first - second);
}