A case of Python operating excel files

黄舟
Release: 2017-10-16 11:05:22
Original
2586 people have browsed it

This article mainly introduces the example code of using Python to operate excel files. Friends who need it can refer to

The class library used

pip install openpyxl

Operation implementation

##•Workbook operation


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

•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"
Copy after login

•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()
Copy after login

Summary

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template