本文主要技术要点:

  • 使用xlrd读取excel文件
  • 使用xlwd写入excel文件
  • excel文件中时间元素的简单计算

1.题目要求

根据如下名为时刻表.xlsx的文件计算每种路线需要的时间,并将结果写入新文件:

2.环境配置

安装需要用到的xlrd和xlwd库:

$ pip install xlrd xlwt

3.读取excel文件

读取文件首先需要打开文件对象,使用xlrd.open_workbook()函数打开文件,该函数返回获取的文件对象。因为excel文件由表组成,我们还需要找到对应的表格才能对表中的元素进行操作,所以需要通过刚才获得的文件对象用成员函数sheet_by_index()找到对应的表,因为文件中只有一个表,所以下标是0,代码如下:

workbook=xlrd.open_workbook('./时刻表.xlsx')
booksheet=workbook.sheet_by_index(0)

根据所需要的“出发时间”和“到达时间”两列的列号是3和5,我们可以这样获得由这两列元素组成的列表:

col_leave=booksheet.col_values(3)
col_arrive=booksheet.col_values(5)

我们也可以根据“出发时间”和“到达时间”两个字段自动找到两列的列号。具体做法是通过读取第二行元素,获得一个包含这两个字段的列表,但是如果通过遍历一次列表找到两个下标的方法并不优雅,我们就想到可以建立一个列表元素到列表下标的映射,然后再通过两个字段直接找到下标:

row_dict=dict(map(reversed,enumerate(booksheet.row_values(1))))
col_leave=booksheet.col_values(row_dict["出发时间"])
col_arrive=booksheet.col_values(row_dict["到达时间"])

4.计算时间差并打印

因为这里时间元素的格式是excel中自定义的时间格式,我们需要通过xlrd.xldate.xldate_as_datetime函数返回时间对象,通过seconds成员返回该时间以秒为单位的值,通过步骤3中两个列表对应元素的差生成列表:

col_result=[(xlrd.xldate.xldate_as_datetime(col_arrive[i],0)-\
        xlrd.xldate.xldate_as_datetime(col_leave[i],0)).seconds/3600 for i in range(2,colNumber)]

注意列表中前两个元素是表头,不是时间值。

5.将结果写入excel新文件

类似之前读取文件,我们用下面的代码获得文件对象进行写入:

new_workbook=xlwt.Workbook()
sheet1=new_workbook.add_sheet('result',cell_overwrite_ok=True)

这里cell_overwrite_ok参数相当于open函数里面的打开方式是否是’w’,我们选择True,也就是覆盖写的方式,每次打开文件的写入操作都会覆盖之前的结果。
接下来通过两层循环和sheet.write()函数向表格写入元素:

for i in range(2):
    for j in range(colNumber-1):
        sheet1.write(j,i,write_result[i][j])

sheet.write函数用到的三个函数分别是写入单元格行号,写入单元格列号,用于写入单元格的元素值,因为我们的列表是2*n的矩阵,所以要成竖排格式需要i和j下标互换。

6.完整代码及结果

#pip install xlrd xlwt

import xlrd
import xlwt
from datetime import datetime
 
workbook=xlrd.open_workbook('./时刻表.xlsx')
booksheet=workbook.sheet_by_index(0)

row_dict=dict(map(reversed,enumerate(booksheet.row_values(1))))
col_leave_index=row_dict["出发时间"]
col_arrive_index=row_dict["到达时间"]

col_leave=booksheet.col_values(col_leave_index)
col_arrive=booksheet.col_values(col_arrive_index)
colNumber=len(col_leave)
col_result=[(xlrd.xldate.xldate_as_datetime(col_arrive[i],0)-\
        xlrd.xldate.xldate_as_datetime(col_leave[i],0)).seconds/3600 for i in range(2,colNumber)]

#print time needed
print("各条线路需要时间\n"+"-"*32)
for i in range(0,len(col_result)):
    print("线路序号"+str(i+1)+"需要"+"{}".format(col_result[i])+"小时")

#write a new xls file
new_workbook=xlwt.Workbook()
sheet1=new_workbook.add_sheet('result',cell_overwrite_ok=True)
write_result=[["线路序号"]+[str(i) for i in range(1,colNumber-1)],["所需时间"]+[str(i) for i in col_result]]

for i in range(2):
    for j in range(colNumber-1):
        sheet1.write(j,i,write_result[i][j])

new_workbook.save('result.xls')

写入的新xls文件截图:

命令行打印截图:

本文地址:https://blog.csdn.net/weixin_44005234/article/details/109830666