以下是完善后的程序:

import openpyxl
from openpyxl.utils import column_index_from_string
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
from math import sqrt

# 打开原始excel文件
filename = input("请输入要处理的excel文件名(包括后缀名):")
wb = openpyxl.load_workbook(filename)
sheet = wb.active

# 在第一行添加“距离”列的标题
sheet.insert_cols(3)
sheet.cell(row=1, column=3).value = "距离"
sheet.cell(row=1, column=3).font = Font(bold=True)

# 遍历每一行,计算每组两个点之间的距离,并将结果写入“距离”列
for i in range(2, sheet.max_row + 1):
    x1 = sheet.cell(row=i, column=1).value
    y1 = sheet.cell(row=i, column=2).value
    x2 = sheet.cell(row=i, column=4).value
    y2 = sheet.cell(row=i, column=5).value
    distance = round(sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2), 2)
    sheet.cell(row=i, column=3).value = distance

# 保存新的excel文件
new_filename = "new_" + filename
wb.save(new_filename)
print("新的excel文件已保存为:", new_filename)

注:假设原始excel文件中的数据分别存储在第一列、第二列、第四列、第五列中。


原文地址: http://www.cveoy.top/t/topic/bwY7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录