如何基于CSS样式程序化将Div布局转换为HTML表格?
Div转HTML表格的程序化转换需求
项目背景
我正在开展一个项目,需将采用<div>元素设计的复杂布局,通过<table>、<tr>、<td>、<colspan>和<rowspan>标签转换为HTML表格。当前布局由CSS样式控制,转换后需保留原有结构与外观。
输入内容
我有一系列代表表格表头和数据单元格的<div>元素,每个<div>带有多个类属性,对应定义其位置和尺寸的CSS样式。以下是当前基于Div的布局片段:
<div class="c x1b y41 wf h14">Project</div> <div class="c x20 y43 w10 h6">2023</div> <div class="c x21 y43 w11 h6">2022</div> <div class="c x23 y43 w12 h6">2021</div> <div class="c x1e y43 w13 h6">2020</div> <div class="c x20 y41 w14 h9">Amount</div> <div class="c x26 y41 w15 h9">Ratio</div> <div class="c x21 y41 w16 h9">Amount</div> <div class="c x28 y41 w17 h9">Ratio</div> <div class="c x23 y41 w18 h9">Amount</div> <div class="c x29 y41 w19 h9">Ratio</div> <div class="c x1e y41 w1a h9">Amount</div> <div class="c x2a y41 w1b h9">Ratio</div> <div class="c x1b y44 wf h6">Income</div> <div class="c x20 y44 w14 h6">9.6</div> <div class="c x26 y44 w15 h6">100.00</div> <div class="c x21 y44 w16 h6">377.78</div> <div class="c x28 y44 w17 h6">100.00</div> <div class="c x23 y44 w18 h6">293.47</div> <div class="c x29 y44 w19 h6">100.00</div> <div class="c x1e y44 w1a h6">210.66</div> <div class="c x2a y44 w1b h6">100.00</div>
CSS样式
布局由以下CSS样式控制,规定了Div的尺寸与位置:
.h14 {height: 41.215200px;} .h6 {height: 20.280000px;} .h9 {height: 20.311200px;} .w10 {width: 116.095200px;} .w11 {width: 116.251200px;} .w12 {width: 116.376000px;} .w13 {width: 122.959200px;} .w14 {width: 55.099200px;} .w15 {width: 60.216000px;} .w16 {width: 58.188000px;} .w17 {width: 57.283200px;} .w18 {width: 61.152000px;} .w19 {width: 54.600000px;} .w1a {width: 61.963200px;} .w1b {width: 60.372000px;} .wf {width: 73.008000px;} .x1b {left: 112.450000px;} .x1e {left: 537.830800px;} .x20 {left: 186.914000px;} .x21 {left: 303.641000px;} .x23 {left: 420.511000px;} .x26 {left: 242.801000px;} .x28 {left: 362.609000px;} .x29 {left: 482.287000px;} .x2a {left: 600.262000px;} .y41 {bottom: 490.373000px;} .y43 {bottom: 511.303000px;} .y44 {bottom: 469.313000px;}
预期结果
我希望将此布局转换为如下结构的HTML表格:
<table border="1"> <tr> <td rowspan="2">Project</td> <td colspan="2">2023</td> <td colspan="2">2022</td> <td colspan="2">2021</td> <td colspan="2">2020</td> </tr> <tr> <td>Amount</td> <td>Ratio</td> <td>Amount</td> <td>Ratio</td> <td>Amount</td> <td>Ratio</td> <td>Amount</td> <td>Ratio</td> </tr> <tr> <td>Income</td> <td>9.6</td> <td>100.00</td> <td>377.78</td> <td>100.00</td> <td>293.47</td> <td>100.00</td> <td>210.66</td> <td>100.00</td> </tr> </table>
(注:修正了原预期结果中<td>9.6</div></td>的语法错误)
已尝试方案
我尝试过多种解析Div并应用样式生成表格的方法,但效果不佳。曾用JavaScript动态读取CSS属性并将其应用为表格单元格属性,但在维持布局完整性(尤其是行/列合并)方面遇到问题。
问询
能否提供基于CSS样式将此Div布局程序化转换为HTML表格的指导或解决方案?尤其希望获得解析CSS以确定表格合适的<colspan>和<rowspan>值的相关帮助。
内容的提问来源于stack exchange,提问作者Tough Hou
相关产品推荐
相关产品推荐

