style: оформление выгрузки в Excel «как в ГРАНД-Смете»

styles.xml в xlsx-генераторе: жирная серая шапка с рамками и центрированием,
рамки на всех ячейках, формат рублей (#,##0.00) для денежных колонок и
0.###### для количеств (без потери точности), ширины колонок по содержимому,
перенос «Наименования», жирная строка «Итого», закрепление шапки, титул из
заголовка markdown (объединённая ячейка). Шифры остаются текстом. Проверено
openpyxl: 0 warnings, стили/форматы/рамки/заморозка корректны.
This commit is contained in:
anor
2026-06-09 18:04:22 +10:00
parent 87603a9adf
commit c0608d71f0
+95 -15
View File
@@ -262,6 +262,12 @@ function enhanceTables(container) {
if (th) th.classList.add('num');
}
}
// заголовок для Excel — ближайший предшествующий заголовок markdown (до обёртки)
let title = '';
for (let p = table.previousElementSibling; p; p = p.previousElementSibling) {
if (p.tagName === 'TABLE') break;
if (/^H[1-6]$/.test(p.tagName) && p.textContent.trim()) { title = p.textContent.trim().slice(0, 120); break; }
}
const wrap = document.createElement('div');
wrap.className = 'table-wrap';
table.parentNode.insertBefore(wrap, table);
@@ -271,7 +277,7 @@ function enhanceTables(container) {
bar.className = 'msg-table-bar';
const btn = document.createElement('button');
btn.textContent = '⤓ Скачать в Excel';
btn.onclick = () => tableToExcel(table, 'смета.xlsx');
btn.onclick = () => tableToExcel(table, 'смета.xlsx', title);
bar.appendChild(btn);
wrap.parentNode.insertBefore(bar, wrap);
});
@@ -330,28 +336,100 @@ function _asNumber(s) {
const t = s.replace(/[\s\u00a0\u202f\u2009\u2007]/g, '').replace(',', '.');
return /^-?\d+(\.\d+)?$/.test(t) ? t : null;
}
function tableToExcel(table, filename) {
// Тип колонки по тексту шапки: денежная / количественная / номер / прочая.
function _colKind(h) {
h = (h || '').toLowerCase();
if (/№|п\/п/.test(h)) return 'idx';
if (/руб|стоим|цена|сумм|итог|всего/.test(h)) return 'money';
if (/кол|объ[её]м/.test(h)) return 'qty';
return 'auto';
}
// Оформление «как в ГРАНД-Смете»: шрифты, серая шапка, рамки, форматы чисел.
// Индексы cellXfs: 0 default,1 шапка,2 текст,3 деньги,4 кол-во,5 итог-число,
// 6 итог-текст,7 титул,8 номер-по-центру.
const _XLSX_STYLES =
'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
'<numFmts count="2"><numFmt numFmtId="164" formatCode="#,##0.00"/><numFmt numFmtId="165" formatCode="0.######"/></numFmts>' +
'<fonts count="3">' +
'<font><sz val="9"/><name val="Arial"/></font>' +
'<font><b/><sz val="9"/><name val="Arial"/></font>' +
'<font><b/><sz val="11"/><name val="Arial"/></font>' +
'</fonts>' +
'<fills count="3">' +
'<fill><patternFill patternType="none"/></fill>' +
'<fill><patternFill patternType="gray125"/></fill>' +
'<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/><bgColor indexed="64"/></patternFill></fill>' +
'</fills>' +
'<borders count="2">' +
'<border><left/><right/><top/><bottom/><diagonal/></border>' +
'<border><left style="thin"><color rgb="FF808080"/></left><right style="thin"><color rgb="FF808080"/></right><top style="thin"><color rgb="FF808080"/></top><bottom style="thin"><color rgb="FF808080"/></bottom><diagonal/></border>' +
'</borders>' +
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
'<cellXfs count="9">' +
'<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
'<xf numFmtId="0" fontId="1" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>' +
'<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="top" wrapText="1"/></xf>' +
'<xf numFmtId="164" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
'<xf numFmtId="165" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
'<xf numFmtId="164" fontId="1" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
'<xf numFmtId="0" fontId="1" fillId="0" borderId="1" xfId="0" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center" wrapText="1"/></xf>' +
'<xf numFmtId="0" fontId="2" fillId="0" borderId="0" xfId="0" applyFont="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>' +
'<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>' +
'</cellXfs>' +
'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
'</styleSheet>';
function tableToExcel(table, filename, title) {
const enc = new TextEncoder();
const rows = [...table.rows].map(tr => [...tr.cells].map(td =>
td.textContent.replace(/[\u00a0\u202f\u2009\u2007]/g, ' ').trim()));
if (!rows.length) return;
const nCols = Math.max(...rows.map(r => r.length));
const header = rows[0] || [];
const kinds = [], widths = [];
for (let c = 0; c < nCols; c++) {
kinds[c] = _colKind(header[c]);
let mx = 6;
for (const r of rows) if (r[c]) mx = Math.max(mx, r[c].length);
widths[c] = Math.min(50, Math.max(6, mx + 2));
}
const base = title ? 1 : 0; // строка-титул сверху
let rowsXml = '';
[...table.rows].forEach((tr, ri) => {
if (title) rowsXml += `<row r="1"><c r="A1" t="inlineStr" s="7"><is><t xml:space="preserve">${_xmlEsc(title)}</t></is></c></row>`;
rows.forEach((cells, ri) => {
const rr = ri + 1 + base;
const isHeader = ri === 0;
const isTotal = !isHeader && cells.some(t => /итог|всего|подыто/i.test(t));
let cellsXml = '';
[...tr.cells].forEach((td, ci) => {
const ref = _colName(ci) + (ri + 1);
const text = td.textContent.replace(/[\u00a0\u202f\u2009\u2007]/g, ' ').trim();
const num = ri === 0 ? null : _asNumber(text); // шапку всегда текстом
cellsXml += num !== null
? `<c r="${ref}"><v>${num}</v></c>`
: `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${_xmlEsc(text)}</t></is></c>`;
});
rowsXml += `<row r="${ri + 1}">${cellsXml}</row>`;
for (let c = 0; c < nCols; c++) {
const ref = _colName(c) + rr;
const text = cells[c] || '';
const num = isHeader ? null : _asNumber(text);
let s;
if (isHeader) s = 1;
else if (num !== null) s = isTotal ? 5 : (kinds[c] === 'money' ? 3 : kinds[c] === 'idx' ? 8 : 4);
else s = isTotal ? 6 : 2;
if (num !== null) cellsXml += `<c r="${ref}" s="${s}"><v>${num}</v></c>`;
else if (text) cellsXml += `<c r="${ref}" t="inlineStr" s="${s}"><is><t xml:space="preserve">${_xmlEsc(text)}</t></is></c>`;
else cellsXml += `<c r="${ref}" s="${s}"/>`;
}
rowsXml += `<row r="${rr}">${cellsXml}</row>`;
});
const lastCol = _colName(nCols - 1);
const colsXml = '<cols>' + widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('') + '</cols>';
const freeze = base + 1; // закрепить титул(если есть)+шапку
const viewsXml = `<sheetViews><sheetView workbookViewId="0"><pane ySplit="${freeze}" topLeftCell="A${freeze + 1}" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft"/></sheetView></sheetViews>`;
const mergeXml = title ? `<mergeCells count="1"><mergeCell ref="A1:${lastCol}1"/></mergeCells>` : '';
const X = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
const sheetXml = X + '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
viewsXml + colsXml + '<sheetData>' + rowsXml + '</sheetData>' + mergeXml + '</worksheet>';
const files = [
{name: '[Content_Types].xml', bytes: enc.encode(X +
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
'<Default Extension="xml" ContentType="application/xml"/>' +
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
'<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>')},
{name: '_rels/.rels', bytes: enc.encode(X +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
@@ -361,9 +439,10 @@ function tableToExcel(table, filename) {
'<sheets><sheet name="Смета" sheetId="1" r:id="rId1"/></sheets></workbook>')},
{name: 'xl/_rels/workbook.xml.rels', bytes: enc.encode(X +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>')},
{name: 'xl/worksheets/sheet1.xml', bytes: enc.encode(X +
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>' + rowsXml + '</sheetData></worksheet>')},
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')},
{name: 'xl/styles.xml', bytes: enc.encode(X + _XLSX_STYLES)},
{name: 'xl/worksheets/sheet1.xml', bytes: enc.encode(sheetXml)},
];
const blob = new Blob([_zipStore(files)], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
const url = URL.createObjectURL(blob);
@@ -373,6 +452,7 @@ function tableToExcel(table, filename) {
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
// Лёгкая типографика прозы AI (Ководство): м²/м³, знак умножения, тире.
// СТРОГО минует таблицы и код — там шифры расценок (01-01-001), их дефисы
// и числа трогать нельзя. Идемпотентна (² не матчит 2 повторно).