import { saveAs } from 'file-saver'
import XLSX from 'xlsx'
export function exportElementTable(el, filename) {
const clonedEl = el.cloneNode(true)
const fixedElements = clonedEl.querySelectorAll('.el-table__fixed, .el-table__fixed-right, .el-table__fixed-left')
if (fixedElements && fixedElements.length > 0) {
for (let i = 0; i < fixedElements.length; i++) {
const fixedEl = fixedElements[i]
if (fixedEl.parentNode) {
fixedEl.parentNode.removeChild(fixedEl)
}
}
}
const headerTable = clonedEl.querySelector('.el-table__header-wrapper table')
const bodyTable = clonedEl.querySelector('.el-table__body-wrapper table')
const mergedTable = document.createElement('table')
if (headerTable && headerTable.className) {
mergedTable.setAttribute('class', headerTable.className)
}
if (headerTable) {
const thead = document.createElement('thead')
const headerRows = headerTable.getElementsByTagName('tr')
if (headerRows && headerRows.length > 0) {
for (let i = 0; i < headerRows.length; i++) {
const tr = headerRows[i]
thead.appendChild(tr.cloneNode(true))
}
}
mergedTable.appendChild(thead)
}
if (bodyTable) {
const tbody = document.createElement('tbody')
const bodyRows = bodyTable.getElementsByTagName('tr')
if (bodyRows && bodyRows.length > 0) {
for (let i = 0; i < bodyRows.length; i++) {
const tr = bodyRows[i]
tbody.appendChild(tr.cloneNode(true))
}
}
mergedTable.appendChild(tbody)
}
const allCells = mergedTable.getElementsByTagName('th')
const dataCells = mergedTable.getElementsByTagName('td')
const combinedCells = [].concat(Array.from(allCells), Array.from(dataCells))
for (let i = 0; i < combinedCells.length; i++) {
const cell = combinedCells[i]
if (cell) {
const rowSpan = cell.getAttribute('data-rowspan') || 1
const colSpan = cell.getAttribute('data-colspan') || 1
if (rowSpan > 1) {
cell.setAttribute('rowspan', rowSpan)
}
if (colSpan > 1) {
cell.setAttribute('colspan', colSpan)
}
}
}
const workbook = XLSX.utils.table_to_book(mergedTable, {
raw: true,
display: true,
cellDates: true,
})
const wbout = XLSX.write(workbook, {
bookType: 'xlsx',
bookSST: true,
type: 'array',
})
saveAs(
new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
`${filename}.xlsx`
)
}
