行列操作指南¶
本页面详细介绍行和列的各种操作。
行操作¶
插入行¶
删除行¶
设置行高¶
隐藏行¶
显示行¶
列操作¶
插入列¶
删除列¶
设置列宽¶
隐藏列¶
显示列¶
自动调整¶
自动列宽¶
自动行高¶
完整示例¶
示例1: 动态调整¶
from symphra_excel import Workbook
with Workbook() as wb:
sheet = wb.create_worksheet("动态表格")
headers = ["序号", "姓名", "电子邮件地址", "备注"]
for col_idx, header in enumerate(headers, start=1):
cell = f"{chr(64+col_idx)}1"
sheet.set_cell_value(cell, header)
data = [
[1, "张三", "zhangsan@example.com", "优秀员工"],
[2, "李四", "lisi@example.com", "新入职"],
]
for row_idx, row in enumerate(data, start=2):
for col_idx, value in enumerate(row, start=1):
sheet.set_cell_value(f"{chr(64+col_idx)}{row_idx}", value)
sheet.set_column_width("A", 8)
sheet.set_column_width("B", 12)
sheet.set_column_width("C", 25)
sheet.set_column_width("D", 15)
sheet.set_row_height(1, 25)
wb.save("dynamic_table.xlsx")
示例2: 插入统计行¶
from symphra_excel import Workbook
with Workbook() as wb:
sheet = wb.create_worksheet("销售数据")
headers = ["日期", "销售额", "利润"]
for col_idx, header in enumerate(headers, start=1):
sheet.set_cell_value(f"{chr(64+col_idx)}1", header)
data = [
["2024-01-01", 1000, 300],
["2024-01-02", 1500, 450],
["2024-01-03", 1200, 360],
]
for row_idx, row in enumerate(data, start=2):
for col_idx, value in enumerate(row, start=1):
sheet.set_cell_value(f"{chr(64+col_idx)}{row_idx}", value)
total_row = len(data) + 2
sheet.set_cell_value(f"A{total_row}", "总计")
sheet.set_cell_value(f"B{total_row}", f"=SUM(B2:B{total_row-1})")
sheet.set_cell_value(f"C{total_row}", f"=SUM(C2:C{total_row-1})")
wb.save("sales_with_totals.xlsx")
最佳实践¶
✅ 推荐做法¶
for col in ["A", "B", "C"]:
sheet.set_column_width(col, 12)
for row in range(1, 11):
sheet.set_row_height(row, 20)
sheet.insert_rows(2, 1)
sheet.set_cell_value("A2", "新行数据")
❌ 避免的做法¶
sheet.set_column_width("A", 500)
for i in range(10000):
sheet.insert_rows(1, 1)
sheet.delete_rows(1, 100)