
本文详解如何将 HTML 表格中 input 元素的当前值(而非初始 placeholder 或空值)正确注入 jsPDF AutoTable,特别适用于带日期、用户输入和固定字段(如电话)的月度排班表导出场景。
本文详解如何将 html 表格中 input 元素的当前值(而非初始 placeholder 或空值)正确注入 jspdf autotable,特别适用于带日期、用户输入和固定字段(如电话)的排班表导出场景。
在使用 要真正实现“动态值注入”,必须绕过 HTML 解析,转为手动构建数据结构:先获取表格行数(如当月天数),再逐行读取对应 input 元素的实时 以下是一个生产就绪的实现方案: ⚠️ 关键注意事项: 立即学习“前端免费学习笔记(深入)”; 通过此方法,你不仅能精准导出用户填写的排班信息,还可灵活扩展(如添加状态标记、颜色高亮、多级表头等),真正实现「所见即所得」的 PDF 导出体验。jsPDF-AutoTable 导出 HTML 表格时,一个常见误区是直接调用 autoTableHtmlToJson() —— 该方法仅提取 <td> 的 innerText 或 <code><input> 的 value 属性初始值(即 DOM 加载时的静态值),而无法捕获用户后续在 input 中手动输入或从 localStorage 动态填充的新内容。value,并组合成符合 AutoTable body 格式的数组。function createMonthlySchedulePDF(month, year) {
const pdf = new jsPDF({
orientation: 'p',
unit: 'mm',
format: 'a4',
putOnlyUsedFonts: true
});
// 计算当月总天数(推荐使用 dayjs 或原生 Date,此处以 dayjs 为例)
const daysInMonth = dayjs(`${year}-${String(month + 1).padStart(2, '0')}`, 'YYYY-MM').daysInMonth();
// 构建 body 数据:每行 = [日期, 输入值, 电话]
const body = [];
for (let day = 1; day <= daysInMonth; day++) {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
// ✅ 关键:动态获取 input 值(假设 input 的 id 格式为 `input-${dateStr}`)
const inputEl = document.getElementById(`input-${dateStr}`);
const inputValue = inputEl ? inputEl.value.trim() : '';
// ✅ 同样动态获取电话(如存在对应 phone-${dateStr} 元素)
const phoneEl = document.getElementById(`phone-${dateStr}`);
const phoneValue = phoneEl ? phoneEl.textContent.trim() : '';
body.push([
dateStr, // 第一列:日期
inputValue, // 第二列:input 实时值(非 localStorage 静态键!)
phoneValue // 第三列:电话(可为 textContent 或 data-attr)
]);
}
// 渲染 AutoTable
pdf.autoTable({
startY: 30,
tableWidth: 'auto',
theme: 'grid',
head: [['日期', '值班人员', '联系电话']], // 表头需与 body 列数严格一致
body: body,
headStyles: {
fillColor: '#a9a6a6',
textColor: '#000000'
},
columnStyles: {
0: { cellWidth: 25 }, // 日期列稍宽
1: { cellWidth: 45 }, // 人员列适中
2: { cellWidth: 40 } // 电话列
}
});
pdf.save(`月度排班_${year}年${month + 1}月.pdf`);
}
localStorage.getItem('key name') 硬编码键名:实际场景中,每个日期应有唯一 key(如 'schedule_2024-06-01'),且需与 input 元素一一映射;document.getElementById() 或 querySelector() 获取实时 DOM 值:这是确保导出内容与用户所见完全一致的唯一可靠方式;nextTick 或 flushSync 确保 DOM 已更新;autoTableHtmlToJson() 仅适合纯静态表格;含表单控件的表格必须手动构造 body。



















