Home  >  Article  >  Backend Development  >  Use Python to operate excel files

Use Python to operate excel files

一个新手
一个新手Original
2017-10-17 09:20:581995browse

Class library used

pip install openpyxl

Operation implementation

  • Workbook operation


# coding: utf-8from openpyxl import Workbook
# 创建一个excel工作簿wb = Workbook()
# 打开一个工作簿wb = load_workbook('test.xlsx')
# 保存工作簿到文件wb.save('save.xlsx')
  • Worksheet operations


# 获得当前的工作表对象
ws = wb.active
# 通过工作表名称得到工作表对象
ws = wb.get_sheet_by_name('sheet')
# 获取工作簿的所有工作表对象列表
ws = wb。get_sheet_names()
# 在工作簿末尾创建一个工作表
ws = wb.create_sheet()
# 在第一个位置创建一个工作表
ws = wb.create_sheet(0)
# 修改工作表名称
ws.title = "new sheet"
  • Data operations

  # 使用一个单元格
# 使用一个单元格
# 根据索引获得单元格内容
res = ws['A4']
# 使用cell方法获取单元格
res = ws.cell('A4')
# 或
res = ws.cell(row = 4, column = 1)
# 创建100*100的单元格
for i in range(1,101) for j in range (1,101) ws.cell(row = i, column = j)
# 使用切片获取多个单元格
cells = ws['A1':'d4']
# 使用iter_rows()方法获得行和列
t = touple(ws.iter_rows('A1:D4'))
# 使用rows获取所有行
t = ws.rows()
# 使用columns()获取所有列
t = ws.columns()

The above is the detailed content of Use Python to operate excel files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn