Python3使用xlrd,xlwt, xlutils进行Excel文件的读写操作

操作之前,需要先理解excel的结构。 Excel 首先需要安装几个库。

  1. xlrd, 这个是用于读取excel
  2. xlwt, 这个是用于写入excel
  3. xlutils, 里面有一些对excel操作的东西
pip install xlrd
pip install xlwt
pip install xlutils

1. 读取excel

# 读取excel中的内容
import xlrd

# 打开一个excel文件
xlsx = xlrd.open_workbook("c:/1.xlsx")

# 使用sheet的索引号来获取表
table = xlsx.sheet_by_index(0)
# 使用sheet的名字来获取表
table = xlsx.sheet_by_name("sheet1")

# 获取第0行第1列的数据
value = table.cell(0, 1).value
value = table.cell_value(0, 1)
value = table.row(0)[2].value

2. 写入excel

# 向excel中写入内容
import xlwt

# 创建一个新的work book
new_workbook = xlwt.workbook()

# 在work book中添加一个sheet
worksheet = new_workbook.add_sheet("sheet1")

# 向sheet (0,0)位置写入 "test"
worksheet.write(0, 0, "test")

# 将work book保存成一个文件
new_workbook.save("d:/save.xlsx")

3. 使用excel格式

from xlutils.copy import copy
import xlwt
import xlrd

# 读取一个模板
tem_excel = xlrd.open_workbook("c:/1.xlsx", formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)

# 设置字体
style = xlwt.XFStyle()

font = xlwt.Font()
font.name = "微软雅黑"
font.blod = True
font.height = 360

style.font = font

borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN

style.borders = borders

alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER

style.alignment = alignment

# 写入内容,而且是带上设置的格式
new_sheet.write(0, 0, "abc", style)