使用应用程序脚本对Google文档中的表格行进行编号
Number table rows in Google Doc using Apps Script
我正在编写一个脚本,该脚本接受文本并将每个段落放在一个编号的表格单元格中。我遇到了一个问题,脚本将每个换行符都算作一个段落,这意味着我的表要么有空单元格,要么编号错误。
以下是工作脚本(减去行编号):
function formatArticle() {
var doc = DocumentApp.getActiveDocument()
var body = doc.getBody();
// Get the paragraphs
var paras = body.getParagraphs();
// Add a table to fill in with copied content
var addTable = body.appendTable();
for (var i=0;i<paras.length;++i) {
// If the paragraph is text, add a table row and insert the content.
if(i % 2 == 0) {
var tr = addTable.appendTableRow();
var text = paras[i].getText();
// Number the table rows as they're added in a cell to the left.
for(var j=0;j<2;j++) {
if(j == 0) {
var td = tr.appendTableCell(i);
} else {
var td = tr.appendTableCell(text);
}
}
}
// Shrink left column.
addTable.setColumnWidth(0, 65);
// Delete the original text from the document.
paras[i].removeFromParent();
}
}
这里有一个演示谷歌文档,如果有帮助的话,您可以在不设置新文档的情况下查看文本格式。
逻辑
您应该做的是迭代每个段落,并检查该段落是否包含文本。如果是,则添加一行并将文本放入其中,否则跳过该段并跳到下一段。
实施
function formatArticle(){
var doc = DocumentApp.getActiveDocument()
var body = doc.getBody();
// Get the paragraphs
var paras = body.getParagraphs();
var addTable = body.appendTable();
//paragraph index
var pIndex = 0;
for(var i = 0 ; i < paras.length ; i++){
var para = paras[i];
var paraStr = para.editAsText().getText();
// if there is string content in paragraph
if(paraStr.length){
var tr = addTable.appendTableRow();
var td1 = tr.appendTableCell(pIndex);
var td2 = tr.appendTableCell(paraStr);
pIndex ++;
}
para.removeFromParent();
}
// Shrink left column.
addTable.setColumnWidth(0, 65);
}
在这里,您从段落var paraStr = para.editAsText().getText();
中获取字符串,并检查内容是否存在if(paraStr.length)
。如果是,则创建一行,在其中插入段落索引和段落文本。
试试这个:tr.appendTableCell(i/2 +1)
// Number the table rows as they're added in a cell to the left.
for(var j=0;j<2;j++) {
if(j == 0) {
var td = tr.appendTableCell(i/2 +1);
} else {
var td = tr.appendTableCell(text);
}
}
}
相关文章:
- 我应该使用Ng提交还是点击表格
- CSS表格:从列平移到整个表格宽度
- 将HTML表格导出到excel时,无法将数据加载到excel文件中
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- 滚动和表格
- 将谷歌自动完成地址信息放在页面上,而不是表格中
- Google电子表格getValue([cell containing ])不返回制表符
- 打印预览没有应用程序页眉和页脚的html表格
- 区分电子表格中的空单元格和0值
- 使用外部数据创建仪表板(谷歌电子表格)-JavaScript
- 量角器:读取表格内容
- 如何使用Google Sheets API+Javascript阅读电子表格
- 在jquery中生成一个自动前缀编号
- Jquery 读取编号组中选择下拉列表的数组
- 将HTML表格导出到带有文本和图像的excel中
- 如何将jQuery/AAJAX结果放入表格单元格
- 使用应用程序脚本对Google文档中的表格行进行编号
- 允许访问者在表格中选择转盘幻灯片编号
- 表格编号格式&文本添加HTML
- HTML表格,单击行编号