最近搭框架用的openpyxl 2.5.4版本,之前封装的函数有些提示不推荐使用了,我做了一些更新:

代码:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from openpyxl import load_workbook

from openpyxl.styles import Border, Side, Font

import time

class parseExcel(object):

def __init__(self, excelPath):

self.excelPath = excelPath

self.workbook = load_workbook(excelPath) # 加载excel

self.sheet = self.workbook.active # 获取第一个sheet

self.font = Font(color=None)

self.colorDict = {"red": ‘FFFF3030‘, "green": ‘FF008B00‘}

# 设置当前要操作的sheet对象,使用index来获取相应的sheet

def get_sheet_by_index(self, sheet_index):

sheet_name = self.workbook.sheetnames[sheet_index]

self.sheet = self.get_sheet_by_name(sheet_name)

return self.sheet

# 获取当前默认sheet的名字

def get_default_sheet(self):

return self.sheet.title

# 设置当前要操作的sheet对象,使用sheet名称来获取相应的sheet

def get_sheet_by_name(self, sheet_name):

self.sheet = self.workbook[sheet_name]

return self.sheet

# 获取默认sheet中最大的行数

def get_max_row_no(self):

return self.sheet.max_row

# 获取默认 sheet 的最大列数

def get_max_col_no(self):

return self.sheet.max_column

# 获取默认sheet的最小(起始)行号

def get_min_row_no(self):

return self.sheet.min_row

# 获取默认sheet的最小(起始)列号

def get_min_col_no(self):

return self.sheet.min_column

# 获取默认 sheet 的所有行对象,

def get_all_rows(self):

return list(self.sheet.iter_rows())

# return list(self.rows)也可以

# 获取默认sheet中的所有列对象

def get_all_cols(self):

return list(self.sheet.iter_cols())

# return list(self.sheet.columns)也可以

# 从默认sheet中获取某一列,第一列从0开始

def get_single_col(self, col_no):

return self.get_all_cols()[col_no]

# 从默认sheet中获取某一行,第一行从0开始

def get_single_row(self, row_no):

return self.get_all_rows()[row_no]

# 从默认sheet中,通过行号和列号获取指定的单元格,注意行号和列号从1开始

def get_cell(self, row_no, col_no):

return self.sheet.cell(row=row_no, column=col_no)

# 从默认sheet中,通过行号和列号获取指定的单元格中的内容,注意行号和列号从1开始

def get_cell_content(self, row_no, col_no):

return self.sheet.cell(row=row_no, column=col_no).value

# 从默认sheet中,通过行号和列号向指定单元格中写入指定内容,注意行号和列号从1开始

# 调用此方法的时候,excel不要处于打开状态

def write_cell_content(self, row_no, col_no, content, font=None):

self.sheet.cell(row=row_no, column=col_no).value = content

self.workbook.save(self.excelPath)

return self.sheet.cell(row=row_no, column=col_no).value

# 从默认sheet中,通过行号和列号向指定单元格中写入当前日期,注意行号和列号从1开始

# 调用此方法的时候,excel不要处于打开状态

def write_cell_current_time(self, row_no, col_no):

time1 = time.strftime("%Y-%m-%d %H:%M:%S")

self.sheet.cell(row=row_no, column=col_no).value = str(time1)

self.workbook.save(self.excelPath)

return self.sheet.cell(row=row_no, column=col_no).value

def save_excel_file(self):

self.workbook.save(self.excelPath)

if __name__ == ‘__main__‘:

p = parseExcel(u‘D:\\testdata.xlsx‘)

print u"获取默认行:", p.get_default_sheet()

print u"设置sheet索引为1", p.get_sheet_by_index(1)

print u"获取默认sheet:", p.get_default_sheet()

print u"设置sheet索引为0", p.get_sheet_by_index(0)

print u"获取默认sheet:", p.get_default_sheet()

print u"最大行数:", p.get_max_row_no()

print u"最大列数:", p.get_max_col_no()

print u"最小起始行数:", p.get_min_row_no()

print u"最小起始列数:", p.get_min_col_no()

print u"所有行对象:", p.get_all_rows()

print u"所有列对象:", p.get_all_cols()

print u"获取某一列(2):", p.get_single_col(2)

print u"获取某一行(4):", p.get_single_row(4)

print u"取得行号和列号(2,2)单元格:", p.get_cell(2, 2)

print u"取得行号和列号单元格的内容(2,2)", p.get_cell_content(2, 2)

print u"行号和列号写入内容(11,11):‘xiaxiaoxu‘", p.write_cell_content(11, 11, ‘xiaxiaoxu‘)

print u"行号和列号写入当前日期(13,13):", p.write_cell_current_time(13, 13)

另外一个版本

#!/usr/bin/env python

# -*- coding:utf-8 -*-

from openpyxl import load_workbook

from openpyxl.styles import Font

from openpyxl.styles.colors import BLACK

from collections import namedtuple

class ParseExcel(object):

"""解析excel文件"""

def __init__(self, filename):

try:

self.filename = filename

self.__wb = load_workbook(self.filename) #打开excel

except FileNotFoundError as e:

raise e

def get_max_row_num(self, sheet_name):

"""获取最大行号"""

max_row_num = self.__wb[sheet_name].max_row

return max_row_num

def get_max_column_num(self, sheet_name):

"""获取最大列号"""

max_column = self.__wb[sheet_name].max_column

return max_column

def get_cell_value(self, sheet_name, coordinate=None, row=None, column=None):

"""获取指定单元格的数据"""

if coordinate is not None:

try:

return self.__wb[sheet_name][coordinate].value

except Exception as e:

raise e

elif coordinate is None and row is not None and column is not None:

if isinstance(row, int) and isinstance(column, int):

return self.__wb[sheet_name].cell(row=row, column=column).value

else:

raise TypeError('row and column must be type int')

else:

raise Exception("Insufficient Coordinate of cell!")

def get_row_value(self, sheet_name, row):

"""获取某一行的数据"""

column_num = self.get_max_column_num(sheet_name)

row_value = []

if isinstance(row, int):

for column in range(1, column_num + 1):

values_row = self.__wb[sheet_name].cell(row, column).value

row_value.append(values_row)

return row_value

else:

raise TypeError('row must be type int')

def get_column_value(self, sheet_name, column):

"""获取某一列数据"""

row_num = self.get_max_column_num(sheet_name)

column_value = []

if isinstance(column, int):

for row in range(1, row_num + 1):

values_column = self.__wb[sheet_name].cell(row, column).value

column_value.append(values_column)

return column_value

else:

raise TypeError('column must be type int')

def get_all_value_1(self, sheet_name):

"""获取指定表单的所有数据(除去表头)"""

max_row_num = self.get_max_row_num(sheet_name)

max_column = self.get_max_column_num(sheet_name)

values = []

for row in range(2, max_row_num + 1):

value_list = []

for column in range(1, max_column + 1):

value = self.__wb[sheet_name].cell(row, column).value

value_list.append(value)

values.append(value_list)

return values

def get_all_value_2(self, sheet_name):

"""获取指定表单的所有数据(除去表头)"""

rows_obj = self.__wb[sheet_name].iter_rows(min_row=2, max_row=self.__wb[sheet_name].max_row, values_only=True)

values = []

for row_tuple in rows_obj:

value_list = []

for value in row_tuple:

value_list.append(value)

values.append(value_list)

return values

def get_excel_title(self, sheet_name):

"""获取sheet表头"""

title_key = tuple(self.__wb[sheet_name].iter_rows(max_row=1, values_only=True))[0]

return title_key

def get_listdict_all_value(self, sheet_name):

"""获取所有数据,返回嵌套字典的列表"""

sheet_title = self.get_excel_title(sheet_name)

all_values = self.get_all_value_2(sheet_name)

value_list = []

for value in all_values:

value_list.append(dict(zip(sheet_title, value)))

return value_list

def get_list_nametuple_all_value(self, sheet_name):

"""获取所有数据,返回嵌套命名元组的列表"""

sheet_title = self.get_excel_title(sheet_name)

values = self.get_all_value_2(sheet_name)

excel = namedtuple('excel', sheet_title)

value_list = []

for value in values:

e = excel(*value)

value_list.append(e)

return value_list

def write_cell(self, sheet_name, row, column, value=None, bold=True, color=BLACK):

if isinstance(row, int) and isinstance(column, int):

try:

cell_obj = self.__wb[sheet_name].cell(row, column)

cell_obj.font = Font(color=color, bold=bold)

cell_obj.value = value

self.__wb.save(self.filename)

except Exception as e:

raise e

else:

raise TypeError('row and column must be type int')

if __name__ == '__main__':

pe = ParseExcel('sheet1.xlsx')

# print(pe.get_all_value_2('division'))

# print(pe.get_list_nametuple_all_value('division'))

column_row = pe.get_max_column_num('division')

print('最大列号:', column_row)

max_row = pe.get_max_row_num('division')

print('最大行号:', max_row)

cell_value_1 = pe.get_cell_value('division', row=2, column=3)

print('第%d行, 第%d列的数据为: %s' % (2, 3, cell_value_1))

cell_value_2 = pe.get_cell_value('division', coordinate='A5') #coordinate单元格名称

print('A5单元格的数据为: {}'.format(cell_value_2))

value_row = pe.get_row_value('division', 3)

print('第{}行的数据为:{}'.format(3, value_row))

value_column = pe.get_column_value('division', 2)

print('第{}列的数据为:{}'.format(2, value_column))

values_1 = pe.get_all_value_1('division')

print('第一种方式获取所有数据\n', values_1)

values_2 = pe.get_all_value_2('division')

print('第二种方式获取所有数据\n', values_2)

title = pe.get_excel_title('division') #显示所有的title

print('表头为\n{}'.format(title))

dict_value = pe.get_listdict_all_value('division')

print('所有数据组成的嵌套字典的列表:\n', dict_value)

namedtuple_value = pe.get_list_nametuple_all_value('division') #显示元祖列表

print('所有数据组成的嵌套命名元组的列表:\n', namedtuple_value)

pe.write_cell('division', 1, 2, 'Tc_title') #更换excel中的title

python2使用openpyxl版本_python openpyxl 2.5.4 版本 excel常用操作封装相关推荐

  1. anaconda对应python版本_Python基础——如何查看python版本、如何查看多个python版本

    前言 初学者来说,安装python过程是存在一定难度的. 在安装过程中,可能安装了多个python版本,可能安装了anaconda导致有自带的python,同时本身电脑也安装了官方下载的python也 ...

  2. python对excel操作简书_Python实现EXCEL常用操作——pandas简介

    知乎的代码块太丑了,这里的内容就更新到简书了Python实现EXCEL常用操作--pandas简介​www.jianshu.com EXCEL是日常办公最常用的软件,然而遇到数据量特别大(超过10W条 ...

  3. python openpyxl模块追加数据_python openpyxl模块实现excel的读取,新表创建及原数据表追加新数据...

    当实际工作需要把excel表的数据读取出来,或者把一些统计数据写入excel表中时,一个设计丰富,文档便于寻找的模块就会显得特别的有吸引力,本文对openpyxl模块的一些常见用法做一些记录,方便工作 ...

  4. Python中利用openpyxl对Excel的各种相关详细操作(二十一种常用操作<代码+示例>)

    目录 一.对工作簿中对应工作表的相关操作 1.创建工作簿.工作表并指定活动工作表 2.加载创建的工作簿.修改工作表名字 3.复制活动工作表 4.删除指定工作表 二.对工作表中行.列.单元格的相关操作 ...

  5. pandas python2.3版本_应该学习最新版本的 Python 3 还是旧版本的 Python 2?

    应该学习最新版本的 Python 3 还是旧版本的 Python 2? 看到最新Python版本是3.4,但是网上的资料,包括出版的书籍,都是最晚到13年左右,很多细节都不同,语法也过时了. 那此时应 ...

  6. python openpyxl三行代码将列表数据依次加入excel单元格并生成图表

    OpenPyXL OpenPyXl 几乎可以实现所有的 Excel 功能,而且接口清晰,文档丰富,学习成本相对较低. 安装 用 pip 安装 pip install openpyxl 使用 使用pyt ...

  7. 【openpyxl】python处理excel的常用操作

    文章目录 openpyxl 相关处理Excel的python库 openpyxl安装 openpyxl使用 基本概念 创建加载和保存 操作和修改 openpyxl openpyxl是一个处理Excel ...

  8. python的主要版本_Python目前主要有( )两个主要版本。_学小易找答案

    [单选题]中国证券监督管理委员会制定的<上市公司信息披露管理办法>属于: [单选题]下列项目中不属于病人亲属角色特征的是 [填空题]简述CMM的分级结构及其主要特征.(190)答:(1)初 ...

  9. python 数字转化excel行列_Python 3 实现数字转换成Excel列名(10进制到26进制的转换函数)...

    背景: 最近在看一些Python爬虫的相关知识,讲爬取的一些数据写入到Excel表中,当时当列的数目不确定的情况下,如何通过遍历的方式讲爬取的数据写入到Excel中. 开发环境: Python 3  ...

最新文章

  1. 如何看待年仅28岁却亿万身家的码农郭宇宣布从字节跳动退休?
  2. 多元统计第二章证明题_2020年中南大学应用统计硕士考研成功经验分享
  3. 【云计算】Docker删除名称为none的Image镜像
  4. 广搜--(搜索的第一道题)图像有用区域
  5. 用开源项目PhotoView实现图片的双指缩放和双击放大缩小
  6. Codeforce1311B. WeirdSort (冒泡排序)
  7. 数据库基础知识——DDL语言
  8. Java基础入门笔记-字符串
  9. 218.94.78.76:20001/index.php,详解spring中使用Elasticsearch的实例教程
  10. Java开发笔记(六十九)泛型类的定义及其运用
  11. 透视特洛伊木马程序开发技术
  12. 在线编辑Word——插入公式
  13. 慎用!3个容易被打的Python恶搞脚本!
  14. 转专业申请麦吉尔大学计算机,加拿大大学转专业申请秘籍
  15. NodeJS 运行环境
  16. java下载图片到本地,例如从网上下载图片,下载淘宝图片,下载百度图片等
  17. NVL()、NVL2() 函数的用法
  18. easyRtc设置视频清晰度的方法
  19. 动态规划特训:切木棍(UVA10003)区间切分dp
  20. linux 安全模块开发基础知识

热门文章

  1. Windows 系统-桌面管理
  2. windows 7宣布停止xp
  3. 利用citrix xenapp and xendesktop建立你的云桌面
  4. Python WEB 自动化测试实战,项目场景(详细)
  5. wps怎么检查莫名空格_不会用WPS真是血亏!!!WPS这些超好用的功能让你效率翻倍...
  6. 深度 | 人脸识别在安防领域的路还有很长时间要走
  7. 尚学堂python培训的前景
  8. 椭圆形方程的差分解法
  9. 有趣的Hack-A-Sat黑掉卫星挑战赛——卫星平台内存dump
  10. 转载被无数人转载的文章