Python办公自动化之Excel(中)

论坛 期权论坛     
niminba   2021-5-26 12:32   3611   0
<h2>准备<br>
</h2>
<p>首先,我们需要安装依赖包</p>
<div class="blockcode">
<pre class="brush:bash;">
#&nbsp;安装依赖包
pip3&nbsp;install&nbsp;openpyxl</pre>
</div>
<h2>读取数据<br>
</h2>
<p>使用 openpyxl 中的&nbsp;load_workbook(filepath)&nbsp;加载本地一个 Excel 文件,返回结果是一个工作簿对象</p>
<div class="blockcode">
<pre class="brush:py;">
import openpyxl

# 加载本地的Excel文件
wb = openpyxl.load_workbook(file_path)</pre>
</div>
<p>利用工作簿对象,可以获取所有的 Sheet 名称及 Sheet 列表</p>
<div class="blockcode">
<pre class="brush:py;">
def get_all_sheet_names(wb):
    """
    获取所有sheet的名称
    :param wb:
    :return:
    """
    # sheet名称列表
    sheet_names = wb.sheetnames
    return sheet_names


def get_all_sheet(wb):
    """
    获取所有的sheet
    :param wb:
    :return:
    """
    # sheet名称列表
    sheet_names = get_all_sheet_names(wb)

    # 所有sheet
    sheets = []
    for sheet_name in sheet_names:
        sheet = wb[sheet_name]
        sheets.append(sheet)

    return sheets</pre>
</div>
<p>工作簿对象提供了&nbsp;active&nbsp;属性,用于快速获取当前选择的 Sheet</p>
<div class="blockcode">
<pre class="brush:py;">
def get_current_sheet(wb):
    """
    获取当前选择的sheet,默认是最后一个sheet
    :param wb:
    :return:
    """
    # 当前选中的sheet
    current_sheet = wb.active

    return current_sheet</pre>
</div>
<p>另外,也可以通过&nbsp;Sheet 名称去获取某一个特定的 Sheet 对象</p>
<div class="blockcode">
<pre class="brush:py;">
def get_sheet_by_name(wb, sheet_name):
    """
    通过sheetname去查找某一个sheet
    :param wb:
​    :param sheet_name:
    :return:
    """
    sheet_names = get_all_sheet_names(wb)
    if sheet_name in sheet_names:
        result = wb[sheet_name]
    else:
        result = None
    return result</pre>
</div>
<p>使用&nbsp;sheet.max_row&nbsp;和&nbsp;sheet.max_column&nbsp;可以获取当前 Sheet 中的数据行数和列数</p>
<div class="blockcode">
<pre class="brush:py;">
def get_row_and_column_num(sheet):
    """
    获取sheet的行数和列数
    :param sheet:
    :return:
    """
    # 行数
    row_count = sheet.max_row
    # 列数
    column_count = sheet.max_column

    return row_count, column_count

# 行数和列数
row_count, column_count = get_row_and_column_num(sheet)
print('行数和列数分别为:', row_count, column_count)</pre>
</div>
<p>openpyxl 提供 2 种方式来定位一个单元格,分别是:</p>
<ul>
    <li>数字索引,从 1 开始</li>
</ul>
<p>数字索引:行数字索引、列数字索引</p>
<p>比如:row_index=1,column_index=1</p>
<ul>
    <li>行和列组成的字符串索引</li>
</ul>
<p>字符串索引:列由字母组成 + 行索引</p>
<p>比如:A1 对应第一行、第一列的单元格</p>
<p>并且,openpyxl.utils&nbsp;提供了方法,便于&nbsp;列索引&nbsp;在两者之间进行转换</p>
<div class="blockcode">
<pre class="brush:py;">
from openpyxl.utils import get_column_letter, column_index_from_string

def column_num_to_str(num):
    """
    Excel索引列从数字转为字母
    :param num:
    :return:
    """
    return get_column_letter(num)


def column_str_to_num(str):
    """
    Excel索引列,从字母转为数字
    :param str:
    :return:
    """
    return column_index_from_string(str)</pre>
</div>
<p>单元格的获取,同样可以通过上面 2 种索引方式来获取</p>
<div class="blockcode">
<pre class="brush:py;">
def get_cell(sheet, row_index, column_index):
    """
    获取单元格
    :param sheet:
    :param row_index:
    :param column_index:
    :return:
    """
    # openpyxl索引都是从1开始计数,这与xlrd有所不同
    # 获取某一个单元格(二选一)
    # 比如:获取A1单元格的数据,即第一个行、第一列的数据
    # cell_one = sheet['A1']
    cell_one = sheet.cell(row=row_index, column=column_index)
    return cell_one</pre>
</div>
<p>在日常处理 Excel 数据过程中,可能需要判断单元格数据类型,而 openpyxl 并没有提供现成的方法</p>
<p>这里,我们可以通过单元格对象的&nbsp;value&nbsp;属性拿到值,接着使用&nbsp;isinstance&nbsp;方法判断数据类型</p>
<div class="blockcode">
<pre class="brush:py;">
def get_cell_value_and_type(cell):
    """
    获取某一个cell的内容及数据类型
    :param cell:
    :return:
    """
    # 单元格的值
    cell_value = cell.value
    # 单元格的类型
    cell_type = get_cell_value_type(cell_value)

    return cell_value, cell_type

def get_cell_value_type(cell_value):
    """
    获取数据类型
    :param cell_value:
    :return:
    """
    # 其中
    # 0:空
    # 1:数字
    # 2:字符串
    # 3:日期
    # 4:其他
    if not cell_value:
        cell_type = 0
    elif isinstance(cell_value, int) or isinstance(cell_value, float):
        cell_type = 1
    elif isinstance(cell_value, str):
        cell_type = 2
    elif isinstance(cell_value, datetime.datetime):
        cell_type = 3
    else:
        cell_type = 4
    return cell_type</pre>
</div>
<p>单独获取某一行[列]的数据
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP