码迷,mamicode.com
首页 > 编程语言 > 详细

Python 操作 MS Excel 文件

时间:2016-07-10 11:07:23      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

利用 Python 对 Excel 文件进行操作需要使用第三方库: openpyxl,可执行 pip install openpyxl 进行安装

1. 导入 openpyxl 模块

导入 openpyxl 模块后,利用它的 load_workbook() 方法可以打开一个 Excel 文件,该方法使用一个文件名称作为参数,示例如下:

>>> import openpyxl

>>> wb = openpyxl.load_workbook(‘example.xlsx‘)

>>> type(wb)

<class ‘openpyxl.workbook.workbook.Workbook‘>

2. openpyxl 常用方法

可以使用 openpyxl 对象的 get_sheet_names() 方法得到打开的工作薄中存在的所有工作表名称、用 get_sheet_by_name() 方法获取工作表对象、用 active 属性可获取当前活跃工作表的名称:

>>> wb.get_sheet_names()

[‘Sheet1‘, ‘Sheet2‘, ‘Sheet3‘]

>>> sheet = wb.get_sheet_by_name(‘Sheet3‘)

>>> sheet

<Worksheet "Sheet3">

>>> type(sheet)

<class ‘openpyxl.worksheet.worksheet.Worksheet‘>

>>> sheet.title

‘Sheet3‘

>>> anotherSheet = wb.active

>>> anotherSheet

<Worksheet "Sheet1">

3. 获取单元格属性

可以直接使用单元格名称获取指定单元格,同时单元格具有值、行、列、坐标属性,举例如下:

>>> sheet = wb.get_sheet_by_name(‘Sheet1‘)

>>> sheet[‘A1‘]

<Cell Sheet1.A1>

>>> sheet[‘A1‘].value

datetime.datetime(2015, 4, 5, 13, 34, 2)

>>> c = sheet[‘B1‘]

>>> c.value

‘Apples‘

>>> ‘Row ‘ + str(c.row) + ‘, Column ‘ + c.column + ‘ is ‘ + c.value

‘Row 1, Column B is Apples‘

>>> ‘Cell ‘ + c.coordinate + ‘ is ‘ + c.value

‘Cell B1 is Apples‘

>>> sheet[‘C1‘].value

73

4. 使用 cell()

同时也可以使用工作表对象的 cell() 方法来直接指定单元格,使用该方法时要注意,工作表中的行、列都是从1而不是0开始的:

>>> sheet.cell(row=1, column=2)

<Cell Sheet1.B1>

>>> sheet.cell(row=1, column=2).value

‘Apples‘

>>> for i in range(1, 8, 2):

             print(i, sheet.cell(row=i, column=2).value)

1 Apples

3 Pears

5 Apples

7 Strawberries

5. 获取当前工作表中有效数据区域的行数和列数

>>> sheet.max_row

7

>>> sheet.max_column

3

6. 行、列之间的转换

需要使用 get_column_letter、column_index_from_string 这两个方法

>>> from openpyxl.cell import get_column_letter, column_index_from_string

>>> get_column_letter(1)

‘A‘

>>> get_column_letter(2)

‘B‘

>>> get_column_letter(27)

‘AA‘

>>> get_column_letter(900)

‘AHP‘

>>> get_column_letter(sheet.max_column)

‘C‘

>>> column_index_from_string(‘A‘)

1

>>> column_index_from_string(‘AA‘)

27

7. 获取区域数据

>>> tuple(sheet[‘A1‘:‘C3‘])

((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>, <Cell Sheet1.B2>, <Cell Sheet1.C2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>, <Cell Sheet1.C3>))

8. 获取指定一行或一列数据

>>> sheet.columns[1]

(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>, <Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)

 9. 总结

利用 openpyxl 对 excel 文件进行操作,主要步骤有以下几点:

  • 导入 openpyxl 模块
  • 调用 openpyxl.load_workbook() 函数
  • 获得 Workbook 对象
  • 读取活跃工作表变量或者调用 get_sheet_by_name() 方法
  • 获得 Worksheet 对象
  • 使用索引或使用行、列关键词调用工作表的 cell() 方法
  • 获得 Cell 对象
  • 读取 Cell 对象的属性值

Python 操作 MS Excel 文件

标签:

原文地址:http://www.cnblogs.com/wuzhiblog/p/pythonexcel.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!