帮我优化一下代码 for n in range(len(df)): cells1 = table.rows[n + 6].cells cells1[1].add_paragraph(str(df.iloc[n,0].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[2].add_paragraph(str(df.iloc[n,1].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[3].add_paragraph(str(df.iloc[n,2].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[4].add_paragraph(str(df.iloc[n,3].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[5].add_paragraph(str(df.iloc[n,4].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[6].add_paragraph(str(df.iloc[n,5].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cells1[7].add_paragraph(str(df.iloc[n,6].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
时间: 2023-06-13 15:03:48 浏览: 369
利用Aspose.Cells实现万能导出功能
你可以将这个 for 循环的代码进一步优化,使用一个嵌套的 for 循环来遍历表格中的每个单元格,并设置单元格的文本和对齐方式,这样可以减少代码的重复:
```
# 遍历表格中的每个单元格
for row in table.rows:
for cell_idx, cell in enumerate(row.cells):
# 设置每个单元格的文本和对齐方式
if cell_idx > 0:
cell.add_paragraph(str(df.iloc[cell_idx-1, cell_idx-1].round(3))).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
```
这样可以大大减少代码量,并提高代码的可读性和可维护性。
阅读全文