Python使用openpyxl模块读写excel文件

Python使用openpyxl模块读写excel文件

openpyxl是一个用于写入和读取xlsx格式的excel文件的Python模块。

excel2010后的后缀名为xlsx,不再是xls,使用openpyxl是最适合对xlsx文件进行读取的库。

一、安装openpyxl

pip install openpyxl

二、使用openpyxl将数据写入excel文件

import openpyxl


openpyxl_data = [
    ('我', '们', '在', '这', '寻', '找'),
    ('我', '们', '在', '这', '失', '去'),
    ('p', 'y', 't', 'h', 'o', 'n')
]
output_file_name = 'openpyxl_file.xlsx'


def save_excel(target_list, output_file_name):
    """
    将数据写入xlsx文件
    """
    if not output_file_name.endswith('.xlsx'):
        output_file_name += '.xlsx'

    # 创建一个workbook对象,而且会在workbook中至少创建一个表worksheet
    wb = openpyxl.Workbook()
    # 获取当前活跃的worksheet,默认就是第一个worksheet
    ws = wb.active
    title_data = ('a', 'b', 'c', 'd', 'e', 'f')
    target_list.insert(0, title_data)
    rows = len(target_list)
    lines = len(target_list[0])
    for i in range(rows):
        for j in range(lines):
            ws.cell(row=i + 1, column=j + 1).value = target_list[i][j]

    # 保存表格
    wb.save(filename=output_file_name)


save_excel(openpyxl_data, output_file_name)

代码描述:

1.我们先将需要保存的数据解析好,保存成固定的数据类型(一个由元组或列表构成的列表)

2.我们将保存数据到excel文件的代码封装成一个函数,方便重用

主要步骤为:

(1).创建一个openpyxl.Workbook()对象,也就是创建一个表格对象wb

(2).wb对象中会默认打开一个worksheet,默认是第一张表,使用active方法可以获取到这张表

(3).将数据一个单元格一个单元格的依次写入到表中

(4).保存文件,指定自己想保存成的文件名字

运行结果:

上面的代码执行后,会在代码同级目录下创建一个名字为openpyxl_file.xlsx的excel文件,并写入openpyxl_data的数据,使用excel打开结果如下:

Python使用openpyxl模块读写excel文件_第1张图片

三、使用openpyxl读取excel文件中的数据

import openpyxl


input_file_name = 'openpyxl_file.xlsx'


def read_excel(input_file_name):
    """
    从xlsx文件中读取数据
    """
    workbook = openpyxl.load_workbook(input_file_name)
    print(workbook)
    # 可以使用workbook对象的sheetnames属性获取到excel文件中哪些表有数据
    print(workbook.sheetnames)
    table = workbook.active
    print(table)
    rows = table.max_row
    cols = table.max_column

    for row in range(rows):
        for col in range(cols):
            data = table.cell(row + 1, col + 1).value
            print(data, end=' ')


read_excel(input_file_name)

代码描述:

1.通过openpyxl的load_workbook()方法可以打开一个xlsx文件,返回一个workbook对象,这个对象是一个文件对象

2.可以通过文件对象workbook的sheetnames获取文件中有哪些表是有数据的

3.通过active可以获取到当前的激活的表,默认是第一张sheet,也可以使用workbook的get_sheet_by_name()方法来获取表,返回一个表格对象table

4.通过表格对象table的max_row和max_colum方法可以获取表格中有多少行和列

5.根据行和列就可以读取到表格中每一个单元格的数据了

注意:使用openpyxl读数据时,索引是从1开始的,使用xlrd索引是从0开始的

运行结果:


['Sheet']

a b c d e f 我 们 在 这 寻 找 我 们 在 这 失 去 p y t h o n 

使用openpyxl读取excel数据可以有很多方式实现,可以根据情况灵活使用。

四、使用openpyxl对excel进行高级操作

openpyxl除了常规的写入数据和读取数据外,还提供了非常多的高级操作。

如:设置列宽、行高,设置自动换行,设置文字居中、字体大小、字体颜色,用数据画图等。

做这些操作需要用的方法或函数在openpyxl.utils或openpyxl.styles中可以找到。在实际的使用中,需要用到什么设置可以根据自己的需求去查找对应的方法。

我们就不全部例举了,下面结合写入数据的例子给出一段代码作为参考。

import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, colors, Alignment
import time


openpyxl_data = [
    ('我', '们', '在', '这', '寻', '找'),
    ('我', '们', '在', '这', '失', '去'),
    ('p', 'y', 't', 'h', 'o', 'n')
]
output_file_name = 'openpyxl_file.xlsx'


def save_excel(target_list, output_file_name):
    """
    将数据写入xlsx文件
    """
    if not output_file_name.endswith('.xlsx'):
        output_file_name += '.xlsx'

    # 创建一个workbook对象,而且会在workbook中至少创建一个表worksheet
    wb = openpyxl.Workbook()
    # 获取当前活跃的worksheet,默认就是第一个worksheet
    ws = wb.active
    title_data = ('a', 'b', 'c', 'd', 'e', 'f')
    target_list.insert(0, title_data)
    rows = len(target_list)
    lines = len(target_list[0])
    for i in range(rows):
        for j in range(lines):
            ws.cell(row=i + 1, column=j + 1).value = target_list[i][j]

    # 获取每一列的内容的最大宽度
    i = 0
    col_width = list()
    # 每列
    for col in ws.columns:
        # 每行
        for j in range(len(col)):
            if j == 0:
                # 数组增加一个元素
                col_width.append(len(str(col[j].value)))
            else:
                # 获得每列中的内容的最大宽度
                if col_width[i] < len(str(col[j].value)):
                    col_width[i] = len(str(col[j].value))
        i = i + 1
    # print(col_width)
    # 设置列宽
    for i in range(len(col_width)):
        # 根据列的数字返回字母
        col_letter = get_column_letter(i + 1)
        # 当宽度大于40,宽度设置为45
        if col_width[i] > 40:
            ws.column_dimensions[col_letter].width = 45
            # for j in range(len(list(ws.columns)[i])):
            #     if len(list(ws.columns)[i][j].value) > 40:
            #         ws.row_dimensions[j].height = 15 * (len(list(ws.columns)[i][j].value) // 40 + 1)
        else:
            ws.column_dimensions[col_letter].width = col_width[i] + 3
    # 设置单元格对齐格式
    for col in ws.columns:
        for cell in col:
            cell.alignment = Alignment(horizontal='left', vertical='center', wrap_text=True)
            cell.font = Font(size=10)

    # 设置到期日期超过当前时间的值为红色字体
    for col in ws.columns:
        if col[0].value == '到期日期':
            for j in range(1, len(col)):
                if col[j].value and col[j].value != 'None':
                    due_time = time.mktime(time.strptime(col[j].value, '%Y-%m-%d'))
                    local_time = time.mktime(time.localtime())
                    if int(due_time) <= int(local_time):
                        # print('due_time', int(due_time), 'local_time', int(local_time))
                        col[j].font = Font(color=colors.RED)
    # 保存表格
    wb.save(filename=output_file_name)


save_excel(openpyxl_data, output_file_name)

需要了解更多可以看文档,openpyxl documentation:  https://openpyxl.readthedocs.io/en/stable/

 

Python使用openpyxl模块读写excel文件_第2张图片

 

你可能感兴趣的:(Python/PYPI,openpyxl模块,openpyxl,openpyxl读写excel)