python 操作 xlsx

读取/写入:openpyxl

demo1

import openpyxl
import os


# 创建excel
def write_excel_xlsx(path, sheet_name, value):
    if not os.path.exists(path):
        write_new_excel_xlsx(path, sheet_name, value)
    else:
        append_write_excel_xlsx(path, sheet_name, value)

# 新创建excel
def write_new_excel_xlsx(path, sheet_name, value):
    index = len(value)
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))
    workbook.save(path)
    print("xlsx格式表格写入数据成功!")

# 追加写入
def append_write_excel_xlsx(path, sheet_name, value):
    workbook = openpyxl.load_workbook(path)
    sheet = workbook[sheet_name]
    old_max_row_mum = sheet.max_row # 已存在文件最大的行数
    for i in range(len(value)):
        item = value[i]
        for column in range(len(item)):
            # print(oldRowNum + 1, column + 1, item[column])
            # 参数对应 行, 列, 值
            sheet.cell(row=old_max_row_mum + 1, column=column + 1, value=str(item[column]))
        old_max_row_mum += 1
    workbook.save(path)
    print("xlsx格式表格追加写入数据成功!")


def read_excel_xlsx(path, sheet_name):
    workbook = openpyxl.load_workbook(path)
    # sheet = wb.get_sheet_by_name(sheet_name)这种方式已经弃用,不建议使用
    # sheet = workbook.worksheets[0]
    sheet = workbook[sheet_name]

    # 方式一
    for row in sheet.rows:
        # 收集当前行每个单元格中的数据
        row_text_list = []
        for cell in row:
            row_text_list.append(cell.value)
            print(cell.value, "\t", end="")
        print(row_text_list)  # ["111", "女", "66", "石家庄", "运维工程师"]
        print()

    # 方式二
    for row in sheet.iter_rows(min_row=2):  # 从第二行开始读
        print(row[1].value)

    # 方式三
    for row in sheet.iter_rows(min_row=2, max_row=5):  # 从第2-5行数据
        if row[1].value is None:  # 没有时输出None
            continue
        print(row[1].value)


# 当前文件地址
base_dir = os.path.dirname(os.path.abspath(__file__))  # 'G:\\site\\python\\learn\\base'
book_name_xlsx = os.path.join(base_dir, 'xlsx格式测试工作簿.xlsx')  # 'G:\\site\\python\\learn\\base\\xlsx格式测试工作簿.xlsx'

sheet_name_xlsx = 'xlsx格式测试表'

value1 = [["姓名", "性别", "年龄", "城市", "职业"],
          ["111", "女", "66", "石家庄", "运维工程师"],
          ["222", "男", "55", "南京", "饭店老板"],
          ["333", "女", "27", "苏州", "保安"], ]

value2 = [
    ["444", "男", "55", "南京", "饭店老板"],
    ["55", "女", "27", "苏州", "保安"], ]

write_excel_xlsx(book_name_xlsx, sheet_name_xlsx, value1)
write_excel_xlsx(book_name_xlsx, sheet_name_xlsx, value2)
# read_excel_xlsx(book_name_xlsx, sheet_name_xlsx)

更多文档:

posted @ 2023-05-30 22:36  HaimaBlog  阅读(424)  评论(0编辑  收藏  举报