python读写excel文件简单应用

本文主要技术要点:

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

1.题目要求

根据以下名为时刻表.xlsx的文件计算每种路线须要的时间,并将结果写入新文件:
在这里插入图片描述python

2.环境配置

安装须要用到的xlrd和xlwd库:web

$ pip install xlrd xlwt

3.读取excel文件

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

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

根据所须要的“出发时间”和“到达时间”两列的列号是3和5,咱们能够这样得到由这两列元素组成的列表:svg

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中两个列表对应元素的差生成列表:ui

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)]

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

5.将结果写入excel新文件

相似以前读取文件,咱们用下面的代码得到文件对象进行写入:命令行

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

这里cell_overwrite_ok参数至关于open函数里面的打开方式是不是’w’,咱们选择True,也就是覆盖写的方式,每次打开文件的写入操做都会覆盖以前的结果。
接下来经过两层循环和sheet.write()函数向表格写入元素:excel

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下标互换。code

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文件截图:
在这里插入图片描述
命令行打印截图:
在这里插入图片描述