python操作Excel

openpyxl

读取Excel文件

导入相关函数

 from openpyxl import load_workbook
 # 默认可读写,若有需要可以指定write_only和read_only为True
 wb = load_workbook('pythontab.xlsx')

 

获取工作表--Sheet

 # 获得所有sheet的名称
 print(wb.get_sheet_names())
 # 根据sheet名字获得sheet
 a_sheet = wb.get_sheet_by_name('Sheet1')
 # 获得sheet名
 print(a_sheet.title)
 # 获得当前正在显示的sheet, 也可以用wb.get_active_sheet()
 sheet = wb.active

 

获取单元格

 # 获取某个单元格的值,观察excel发现也是先字母再数字的顺序,即先列再行
 b4 = sheet['B4']
 # 分别返回
 print(f'({b4.column}, {b4.row}) is {b4.value}') # 返回的数字就是int型
 # 除了用下标的方式获得,还可以用cell函数, 换成数字,这个表示B2
 b4_too = sheet.cell(row=4, column=2)
 print(b4_too.value)

 

获得最大行和最大列

 # 获得最大列和最大行
 print(sheet.max_row)
 print(sheet.max_column)

 

获取行和列

 # 因为按行,所以返回A1, B1, C1这样的顺序
 for row in sheet.rows:
   for cell in row:
     print(cell.value)
 # A1, A2, A3这样的顺序
 for column in sheet.columns:
   for cell in column:
     print(cell.value)
 for cell in list(sheet.rows)[2]:
   print(cell.value)

 

获得任意区间的单元格

 for i in range(1, 4):
   for j in range(1, 3):
     print(sheet.cell(row=i, column=j))
 for row_cell in sheet['A1':'B3']:
   for cell in row_cell:
     print(cell)
      
 for cell in sheet['A1':'B3']:
   print(cell)

 

根据字母获得列号,根据列号返回字母

 from openpyxl.utils import get_column_letter, column_index_from_string
 # 根据列的数字返回字母
 print(get_column_letter(2)) # B
 # 根据字母返回列的数字
 print(column_index_from_string('D')) # 4

 

写入Excel

工作表相关

 # 新建了一个新的工作表
 from openpyxl import Workbook
 wb = Workbook()

 

写入单元格

 # 直接给单元格赋值就行
 sheet['A1'] = 'good'
 # B9处写入平均值
 sheet['B9'] = '=AVERAGE(B2:B8)'

 

append函数

可以一次添加多行数据,从第一行空白行开始(下面都是空白行)写入

 # 添加一行
 row = [1 ,2, 3, 4, 5]
 sheet.append(row)
 # 添加多行
 rows = [
   ['Number', 'data1', 'data2'],
   [2, 40, 30],
   [3, 40, 25],
   [4, 50, 30],
   [5, 30, 10],
   [6, 25, 5],
   [7, 50, 10],
 ]

 

按列写入

 list(zip(*rows))
 # out
 [('Number', 2, 3, 4, 5, 6, 7),
  ('data1', 40, 40, 50, 30, 25, 50),
  ('data2', 30, 25, 30, 10, 5, 10)]

 

保存文件

 wb.save(r'D:\example.xlsx')

 

字体

 bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.RED, bold=True)
 sheet['A1'].font = bold_itatic_24_font

 

对齐方式

 sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')

 

设置行高和列宽

# 第2行行高
sheet.row_dimensions[2].height = 40
# C列列宽
sheet.column_dimensions['C'].width = 30

 

合并和拆分单元格

# 合并单元格, 往左上角写入数据即可
sheet.merge_cells('B1:G1') # 合并一行中的几个单元格
sheet.merge_cells('A1:C3') # 合并一个矩形区域中的单元格

 

 

xlrd读取

打开excel文件,获取一个Book()对象

import xlrd
book = xlrd.open_workbook("myfile.xls")

获取sheets数目

book.nsheets

 

获取sheets列表

book.sheets()

 

获取sheets name列表

book.sheet_names()

 

获取Book()中的Sheet

sheet = book.sheets()[0]          #sheets返回一个sheet列表
sheet = book.sheet_by_index(0)    #通过索引顺序获取
sheet = book.sheet_by_name(u'Sheet1')#通过名称获取获取行数,列数,名字:

 

获取行数,列数,名字:

>>> sheet.nrows
1002
>>> sheet.ncols
11
>>> sheet.name
u'Sheet1'

 

 

xlwt生成

创建一个Excel文件并创建一个Sheet

from xlwt import *
book = Workbook()
sheet = book.add_sheet('Sheet1')
book.save('myExcel.xls')

 

向sheet写入内容:

sheet.write(r, c, label="", style=Style.default_style)

 

简单写入:

sheet.write(0, 0, label = 'Row 0, Column 0 Value')

 

设置格式写入:

font = xlwt.Font() # 字体
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # 创建一个格式
style.font = font # 设置格式字体
sheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
book.save('myExcel.xls')

 

写入日期:

style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
sheet.write(0, 0, datetime.datetime.now(), style)

 

写入公式:

sheet.write(0, 0, 5) # Outputs 5
sheet.write(0, 1, 2) # Outputs 2
sheet.write(1, 0, xlwt.Formula('A1*B1')) # 输出 "10" 
sheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # 输出 "7" 

 

写入链接:

sheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) #输出 "Google"链接到http://www.google.com

 

xlutils修改

from xlrd import open_workbook
from xlutils.copy import copy
book = open_workbook('myExcel.xls')
wbook = copy(book)  #wbook即为xlwt.WorkBook对象
wsheet = wbook.get_sheet(0)  #通过get_sheet()获取的sheet有write()方法
wsheet.write(0, 0, 'value')
wb.save('myExcel.xls')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值