docxTable.ts 923 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {
  2. Paragraph,
  3. Table,
  4. TableRow,
  5. TableCell,
  6. } from "docx"
  7. export function convertDomTableToDocxTable(tableEl: HTMLTableElement): Table {
  8. const rows = Array.from(tableEl.rows).map((htmlRow) => {
  9. const cells = Array.from(htmlRow.cells).map((htmlCell) => {
  10. const text = htmlCell.textContent?.trim() || ""
  11. return new TableCell({
  12. children: [new Paragraph(text)],
  13. columnSpan: htmlCell.colSpan > 1 ? htmlCell.colSpan : undefined,
  14. rowSpan: htmlCell.rowSpan > 1 ? htmlCell.rowSpan : undefined,
  15. })
  16. })
  17. return new TableRow({ children: cells })
  18. })
  19. return new Table({ rows })
  20. }
  21. const handleTable = (el: Element): Table | undefined => {
  22. const tag = el.tagName.toLowerCase()
  23. if (tag === "table") {
  24. if (el instanceof HTMLTableElement) {
  25. return convertDomTableToDocxTable(el)
  26. }
  27. }
  28. }
  29. export default {
  30. handleTable,
  31. config: {} // 无配置
  32. }