首页 > 解决方案 > 输出到 Excel 并覆盖现有选项卡

问题描述

我有一个 Python 程序,我在其中使用 SQL 提取数据,现在我需要将其写入现有的 Excel 文件。此新数据应覆盖现有选项卡(同名),保持其他两个完整,以便我可以在更新数据上使用其他两个选项卡中的公式。

我将不胜感激示例代码来帮助我做到这一点。

标签: pythonexcel

解决方案


通过知道我要写入的行和列,我已经完成了类似于 .csv 文件的操作。这是功能:

import csv

def write_csv_cell(filename, row, column, data):
    """This one is solely for .csv files"""
    # read the csv file
    with open(filename, 'r') as f:
        reader = csv.reader(f, delimiter=";")
        mylist = list(reader)
    
    # edit the data
    mylist[row][column] = str(data)

    # (over)write the csv file
    with open(filename, 'w', newline='') as f:
        csv_writer = csv.writer(f, delimiter=";")
        csv_writer.writerows(mylist)

import openpyxl

def write_xlsx_cell(file_name, sheet_name, cell=None, data=None):
    """And this one for xlsx files. Install package with pip (python -m pip install openpyxl)"""
    # open workbook
    book = openpyxl.load_workbook(file_name)
    print(f"This workbook has the following sheets: {book.sheetnames}")
    
    # select sheet
    sheet = book.get_sheet_by_name(sheet_name)
    print(f"You selected {sheet.title}")

    # read cell value
    old_value = sheet[cell].value
    
    # modify cell
    sheet[cell] = data
    print(f"Changed sheet {sheet_name} cell {cell} from {old_value} to {sheet[cell].value}")

    # save/overwrite workbook
    book.save(file_name)


if __name__ == "__main__":
    write_xlsx_cell(file_name="test.xlsx", sheet_name="Sheet1", cell="A1", data="Hey, test")

推荐阅读