这是Python做Excel处理的小白必备的技能,接下来我用20多行代码将它呈现出来
代码如下↓
我没有写注释的好习惯,大家勿喷哈!你们以后写代码最好写注释!
from datetime import datetime
from openpyxl.styles import *
import openpyxl
excel = openpyxl.load_workbook("Dates.xlsx")
excel.create_sheet("Date Time")
excel_sheet = excel.active
dates = {
"Year": datetime.now().year,
"Month": datetime.now().month,
"Day": datetime.now().day,
"Hour": datetime.now().hour,
"Minute": datetime.now().minute,
"Second": datetime.now().second,
}
for dates_name, date_time in dates.items():
excel_sheet.append([dates_name, date_time])
for i in range(1, 7):
excel_sheet["A" + str(i)].font = Font(name='Times New Roman', size=16, bold=True, italic=True, color=colors.BLACK)
for i in range(1, 7):
excel_sheet["B" + str(i)].font = Font(name='Times New Roman', size=14, bold=True, italic=True, color=colors.BLUE)
excel.save("Dates.xlsx")
这还是我用pep8格式写的!!!
代码分析:
导入对应库,openpyxl库自己pip,这个库是写Excel必备的。
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl
# datetime库是为了读取系统时间。
from datetime import datetime
# openpyxl是操控Excel专用的。
from openpyxl.styles import *
import openpyxl
Excel自己新建一个,不做任何操作,命名为Dates.xlsx。
# load_work()函数导入Excel文件。
excel = openpyxl.load_workbook("Dates.xlsx")
# 新建一个sheet。
excel.create_sheet("Date Time")
# 激活work sheet。
excel_sheet = excel.active
下面的代码我就不用多说了哈,将系统的年月日时分秒用字典储存下来。
# 如果想让时间跟精准的话可以将datetime.now().second前面加个float()函数。
dates = {
"Year": datetime.now().year,
"Month": datetime.now().month,
"Day": datetime.now().day,
"Hour": datetime.now().hour,
"Minute": datetime.now().minute,
"Second": datetime.now().second,
}
下面的代码至关重要这是将时间储存到Excel文件的代码。
# 将日期时间写入单元格,一个列表一行。
for dates_name, date_time in dates.items():
excel_sheet.append([dates_name, date_time])
# 设置单元格字体样式。
for i in range(1, 7):
excel_sheet["A" + str(i)].font = Font(name='Times New Roman', size=16, bold=True, italic=True, color=colors.BLACK)
for i in range(1, 7):
excel_sheet["B" + str(i)].font = Font(name='Times New Roman', size=14, bold=True, italic=True, color=colors.BLUE)
# 保存文件。
excel.save("Dates.xlsx")
你学废了吗?是不是很简单?
噢耶