export function huoQuTableElement() {const tableData = []; // 存储表格数据的数组let res = [];// 获取到包含表格的foreignObject元素const foreignObject = document.getElementById('mydctable');if (!foreignObject){return '';}// 获取到表格元素let oldTable = foreignObject.querySelector('table');if (!oldTable){return '';}// 复制表格元素let newTable = oldTable.cloneNode(true);// 将新表格添加到页面中foreignObject.appendChild(newTable);//以下方法将合并后的表格还原为未合并的状态let rows = newTable.rows;for (let i = 0; i < rows.length; i++) {let cells = rows[i].cells;for (let j = 0; j < cells.length; j++) {let cell = cells[j];let rowspan = cell.getAttribute('rowspan');let colspan = cell.getAttribute('colspan');let scope = cell.getAttribute('scope');if (rowspan === null){rowspan = 1}cell.setAttribute('data-original-rowspan', rowspan); // 存储原始的 rowspan 值if (rowspan && parseInt(rowspan) > 1) {let copyContent = cell.innerHTML; // 保存当前单元格的内容for (let k = 1; k < parseInt(rowspan); k++) {let nextRow = rows[i + k];if (nextRow) {if (nextRow && j >= 0 && j < nextRow.cells.length) {let nextCell = nextRow.insertCell(j);nextCell.innerHTML = copyContent; // 复制内容到被合并的位置if (colspan) {nextCell.colSpan = parseInt(colspan); // 添加colspan属性}if (scope) {nextCell.scope = scope; // 添加scope属性}nextCell.style.color = 'white'; // 设置文字颜色为白色nextCell.style.border = '1px solid white'; // 设置表格边框为白色nextCell.setAttribute('data-remove', true); //标记为合并单元格,计算时需要删除}}}cell.removeAttribute('rowspan');cell.innerHTML = copyContent; // 在当前单元格复制内容if (colspan) {cell.colSpan = parseInt(colspan); // 添加colspan属性}if (scope) {cell.scope = scope; // 添加scope属性}}}}//以下方法获取到每个单元格的坐标点和宽高let cells = newTable.querySelectorAll('td, th');// 设置固定的参考点坐标let referenceX = 100; // 参考点的横坐标let referenceY = 100; // 参考点的纵坐标cells.forEach(cell => {let cellText = cell.textContent.trim(); // 单元格内容let cellRect = cell.getBoundingClientRect(); // 单元格位置信息let rowspan = cell.getAttribute('data-original-rowspan'); // 单元格合并信息let dataRemove = cell.getAttribute('data-remove');// 计算单元格左上角坐标相对于固定参考点的偏移量并四舍五入为整数let offsetX = Math.round(cellRect.left - referenceX);let offsetY = Math.round(cellRect.top - referenceY);// 封装单元格数据为 JSON 对象if (rowspan == null || rowspan === 'null' || rowspan === '' || rowspan === undefined){rowspan = 1}if (!dataRemove){let cellData = {content: cellText,rowspan: parseInt(rowspan),x: offsetX,y: offsetY + (Math.round(cellRect.height) * (parseInt(rowspan)-1)),width: Math.round(cellRect.width),height: Math.round(cellRect.height) * parseInt(rowspan)};tableData.push(cellData); // 将单元格数据添加到数组}});const jsonData = JSON.stringify({ rects: tableData });res.push(JSON.parse(jsonData))console.log(res)return res;
}
最后输出的格式如下所示:content是单元格的文字内容。x和y是单元格左上角的坐标点,width和height是单元格的宽高。