python操作EXCEL(.xlsx)的相关笔记
下面代码是python 操作Excel (.xlsx) 的常用功能
#encoding = utf-8
# 一、安装
'''
pip install openpyxl==2.5.4
想要在文件中插入图片文件,需要安装pillow
'''
# 二,创建一个excel文件,并写入不同内容,创建的文件不保存只是在内存,看不见。
from openpyxl import Workbook
import locale
import time
import datetime
from openpyxl import load_workbook
import os
wb = Workbook() #创建一个workbook对象,w大写
ws = wb.active #获取默认sheet
print('默认sheet的名字为:',ws.title) #获取sheet名字
ws['C5'] = '这是一个sheet' #在C5单元格写入内容
ws.append([1,2,3,4,5]) #在有效区域后边(C5)写入多个单元格
wb.save('e:\\b.xlsx') #保存到硬盘
locale.setlocale(locale.LC_CTYPE,'chinese') #设置中文时间格式
now = time.time() #获取当前时间戳
arraryTime = time.localtime(now) #获取时间元组
currentTime = time.strftime('%Y年%m月%d日 %H时%M分%S秒',arraryTime) #自定义时间格式
print(currentTime)
nowtime = datetime.datetime.now() #获取当前时间
ws['B2'] = now
ws['C2'] = currentTime
ws['B3'] = nowtime
wb.save('e:\\b.xlsx')
# 三,创建sheet
ws1 = wb.create_sheet('newsheet') #创建一个新的sheet
ws2 = wb.create_sheet('newsheet2',1) #在指定位置插入一个sheet
ws1.title = '新sheet' #设置sheet 名字
wb.save('e:\\b.xlsx') #保存到硬盘
ws1.sheet_properties.tabColor = 'FFF00F' #设置sheet标签的背景颜色
print('all sheet name: ',wb.sheetnames) #获取所有sheet 名字
print('通过sheet名下标获取sheet: ',wb[wb.sheetnames[2]])
wslist = wb.worksheets #获取全部sheet 对象
for i in wslist:
print(i.title) #遍历sheet 对象获取sheet 名字
print('通过sheet名字获取sheet ',wb['新sheet']) #根据sheet 名字获取sheet对象
print('通过sheet对象下标获取sheet ',wslist[0]) #根据sheet 对象的下标获取sheet 对象
target = wb.copy_worksheet(ws) #copy sheet所有内容
target.title = 'copy'
del wb['copy'] #根据sheet 名删除sheet
w