zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python操作Excel文件(1)

2023-06-13 09:12:58 时间

文章背景:Excel是Window环境下流行的、强大的电子表格应用。openpyxl模块让Python程序能够读取和修改Excel电子表格文件。下面介绍如何通过Python操作Excel文件。

本文的例子将使用一个电子表格example.xlsx。

1 读取Excel文档

(1) 打开Excel文档

import openpyxl, os
os.chdir('E:\\python123')

wb = openpyxl.load_workbook("example.xlsx")
print(type(wb))
<class 'openpyxl.workbook.workbook.Workbook'>

(2) 从工作簿中获取工作表

wb.sheetnames   # The workbook's sheets' names.
['Sheet1', 'Sheet2', 'Sheet3']
sheet = wb['Sheet3']     # Get a sheet from the workbook.
print(sheet.title)       # Get the sheet's title as a string.
Sheet3
anotherSheet = wb.active # Get the active sheet.

(3) 从表中取得单元格

sheet = wb['Sheet1']     # Get a sheet from the workbook.
sheet['A1']              # Get a cell from the sheet.
sheet['A1'].value        # Get the value from the cell.
datetime.datetime(2015, 4, 5, 13, 34, 2)
b = sheet['B1']          # Get another cell from the sheet.
b.value
'Apples'
# Get the row, column, and value from the cell.
'Row %s, Column %s is %s' % (b.row, b.column, b.value)
'Row 1, Column 2 is Apples'
'Cell %s is %s' % (b.coordinate, b.value)
'Cell B1 is Apples'
sheet.cell(row=1, column=2)
sheet.cell(row=1, column=2).value
'Apples'
sheet.max_row      # Get the highest row number.
7
sheet.max_column   # Get the highest column number.
3

(4) 列字母与数字之间的转换

import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string

get_column_letter(1)     # Translate column 1 to a letter.
'A'
column_index_from_string('A') # Get A's number.
1

(5) 从表中取得行和列

tuple(sheet['A1':'C3']) # Get all cells from A1 to 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>))
list(sheet.columns)[1] # Get second column's cells.
(<Cell 'Sheet1'.B1>,
 <Cell 'Sheet1'.B2>,
 <Cell 'Sheet1'.B3>,
 <Cell 'Sheet1'.B4>,
 <Cell 'Sheet1'.B5>,
 <Cell 'Sheet1'.B6>,
 <Cell 'Sheet1'.B7>)

(6) 小结

  1. Import the openpyxl module.
  2. Call the openpyxl.load_workbook() function.
  3. Get a Workbook object.
  4. Use the active or sheetnames attributes.
  5. Get a Worksheet object.
  6. Use indexing or the cell() sheet method with row and column keyword arguments.
  7. Get a Cell object.
  8. Read the Cell object’s value attribute.

参考资料:

[1] Python编程快速上手—让繁琐工作自动化(https://ddz.red/AFTmO

[2] WORKING WITH EXCEL SPREADSHEETS(https://automatetheboringstuff.com/2e/chapter13/