1.读取excel文件,并格式化日期数据
vi 3excel_parsing_and_write_keep_dates.py
#encoding=utf8
#!/usr/bin/env python3
import sys
from datetime import date
from xlrd import open_workbook,xldate_as_tuple
from xlwt import Workbook
input_file=sys.argv[1]
output_file=sys.argv[2]
output_workbook=Workbook()
output_worksheet=output_workbook.add_sheet('jan_2013_output')
with open_workbook(input_file) as workbook:
worksheet=workbook.sheet_by_name('january_2013')
for row_index in range(worksheet.nrows): #sheet里面的行数
row_list_output=[]
for col_index in range(worksheet.ncols): #sheet里面的列数
if worksheet.cell_type(row_index,col_index)==3:
date_cell=xldate_as_tuple(worksheet.cell_value(row_index,col_index),workbook.datemode)
print(date_cell)
date_cell=date(*date_cell[0:3].strftime('%m/%d/%Y')) #3/21/2022
row_list_output.append(date_cell)
output_worksheet.write(row_index,col_index,date_cell) #带日期的格子写入。
else:
non_date_cell=worksheet.cell_value(row_index,col_index)
row_list_output.append(non_date_cell)
output_worksheet.write(row_index,col_index,non_date_cell) #非日期的格子写入非日期的数据
output_workbook.save(output_file)
#结果
python 3excel_parsing_and_write_keep_dates.py sales_2013.xls jan_2013_output2.xls
more jan_2013_output2.xls
Customer ID Customer Name Invoice Number Sale Amount Purchase Date
1234 John Smith 100-0002 1200 1/1/2014
2345 Mary Harrison 100-0003 1425 1/6/2014
3456 Lucy Gomez 100-0004 1390 1/11/2014
4567 Rupert Jones 100-0005 1257 1/18/2014
5678 Jenny Walters 100-0006 1725 1/24/2014
6789 Samantha Donadson 100-0007 1995 1/31/2014
2.总结
(1)cell_type=3 包含的是日期类型的数据。
(2)worksheet.cell_value,cell_value函数引用单元格中的值。
(3)*date_cell:前面的星号,没有星号也可以。
(4)xldate_as_tuple,excel中取到的值,以日期模式保存在元组中。
(5)*date_cell[0:3].strftime('%m/%d/%Y'),将日志转换为特定格式字符串。
(6)output_worksheet.write 传入参数是一个列表。
(7)worksheet.nrows行号,worksheet.ncols列号
(8)date_cell[0:3] 从第一个取,取3个。
(9)xldate_as_tuple 返回一个元组,他的值类似于(year, month, day, hour, minute, nearest_second)