fix: выгрузка в настоящий .xlsx вместо HTML-в-.xls
Старый файл открывался простынёй HTML-тегов в Numbers/LibreOffice (трюк работал только в самом Excel). Теперь генерится валидный OOXML-zip (CRC32 + store-ZIP + XML-части) без зависимостей: шифры расценок — текстом, суммы — числами (суммируются, без потери точности), кириллица цела. Проверено openpyxl: лист читается, типы ячеек корректны.
This commit is contained in:
+89
-13
@@ -271,25 +271,101 @@ function enhanceTables(container) {
|
||||
bar.className = 'msg-table-bar';
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = '⤓ Скачать в Excel';
|
||||
btn.onclick = () => tableToExcel(table, 'смета.xls');
|
||||
btn.onclick = () => tableToExcel(table, 'смета.xlsx');
|
||||
bar.appendChild(btn);
|
||||
wrap.parentNode.insertBefore(bar, wrap);
|
||||
});
|
||||
}
|
||||
|
||||
// Выгрузка HTML-таблицы в файл, открываемый Excel/LibreOffice как лист.
|
||||
// Без внешних библиотек: Excel понимает HTML-таблицу в .xls. UTF-8 BOM —
|
||||
// чтобы кириллица не побилась.
|
||||
// --- Генерация НАСТОЯЩЕГО .xlsx (OOXML zip) без внешних библиотек. ---
|
||||
// Трюк «HTML c расширением .xls» открывался как простыня тегов в Numbers/
|
||||
// LibreOffice — это сырой zip с правильными XML-частями, открывается везде.
|
||||
function _crc32(bytes) {
|
||||
if (!_crc32.t) {
|
||||
const t = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
|
||||
t[n] = c >>> 0;
|
||||
}
|
||||
_crc32.t = t;
|
||||
}
|
||||
let crc = 0xFFFFFFFF;
|
||||
for (let i = 0; i < bytes.length; i++) crc = _crc32.t[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);
|
||||
return (crc ^ 0xFFFFFFFF) >>> 0;
|
||||
}
|
||||
// Сборка zip без сжатия (метод store) — валидный архив, Excel/Numbers открывают.
|
||||
function _zipStore(files) {
|
||||
const enc = new TextEncoder();
|
||||
const u16 = n => [n & 0xFF, (n >>> 8) & 0xFF];
|
||||
const u32 = n => [n & 0xFF, (n >>> 8) & 0xFF, (n >>> 16) & 0xFF, (n >>> 24) & 0xFF];
|
||||
const local = [], central = [];
|
||||
let offset = 0;
|
||||
for (const f of files) {
|
||||
const nameB = enc.encode(f.name);
|
||||
const crc = _crc32(f.bytes), sz = f.bytes.length;
|
||||
const lh = [].concat(u32(0x04034b50), u16(20), u16(0), u16(0), u16(0), u16(0),
|
||||
u32(crc), u32(sz), u32(sz), u16(nameB.length), u16(0));
|
||||
local.push(new Uint8Array(lh), nameB, f.bytes);
|
||||
const ch = [].concat(u32(0x02014b50), u16(20), u16(20), u16(0), u16(0), u16(0), u16(0),
|
||||
u32(crc), u32(sz), u32(sz), u16(nameB.length), u16(0), u16(0), u16(0), u16(0),
|
||||
u32(0), u32(offset));
|
||||
central.push(new Uint8Array(ch), nameB);
|
||||
offset += lh.length + nameB.length + sz;
|
||||
}
|
||||
let cSize = 0; for (const c of central) cSize += c.length;
|
||||
const end = [].concat(u32(0x06054b50), u16(0), u16(0), u16(files.length), u16(files.length),
|
||||
u32(cSize), u32(offset), u16(0));
|
||||
const parts = [...local, ...central, new Uint8Array(end)];
|
||||
let total = 0; for (const p of parts) total += p.length;
|
||||
const out = new Uint8Array(total); let pos = 0;
|
||||
for (const p of parts) { out.set(p, pos); pos += p.length; }
|
||||
return out;
|
||||
}
|
||||
function _colName(i) { let s = ''; i++; while (i > 0) { const m = (i - 1) % 26; s = String.fromCharCode(65 + m) + s; i = Math.floor((i - 1) / 26); } return s; }
|
||||
function _xmlEsc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }
|
||||
// Строгое число: «1 234,56», «0,045», «-5». Шифры «01-02-056-02» (дефисы),
|
||||
// «100 м3», «110%» — НЕ числа, остаются текстом.
|
||||
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) {
|
||||
const html =
|
||||
'<html xmlns:x="urn:schemas-microsoft-com:office:excel"><head>' +
|
||||
'<meta charset="utf-8">' +
|
||||
'<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>' +
|
||||
'<x:Name>Смета</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
|
||||
'</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->' +
|
||||
'<style>td,th{border:1px solid #999;padding:4px;mso-number-format:"\\@";} th{font-weight:bold;}</style>' +
|
||||
'</head><body>' + table.outerHTML + '</body></html>';
|
||||
const blob = new Blob(['', html], {type: 'application/vnd.ms-excel'});
|
||||
const enc = new TextEncoder();
|
||||
let rowsXml = '';
|
||||
[...table.rows].forEach((tr, ri) => {
|
||||
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>`;
|
||||
});
|
||||
const X = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
|
||||
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/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">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')},
|
||||
{name: 'xl/workbook.xml', bytes: enc.encode(X +
|
||||
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
'<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>')},
|
||||
];
|
||||
const blob = new Blob([_zipStore(files)], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url; a.download = filename;
|
||||
|
||||
Reference in New Issue
Block a user