python - 输出到 Excel 并覆盖现有选项卡
问题描述
我有一个 Python 程序,我在其中使用 SQL 提取数据,现在我需要将其写入现有的 Excel 文件。此新数据应覆盖现有选项卡(同名),保持其他两个完整,以便我可以在更新数据上使用其他两个选项卡中的公式。
我将不胜感激示例代码来帮助我做到这一点。
解决方案
通过知道我要写入的行和列,我已经完成了类似于 .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")
推荐阅读
- javascript - 如何使用js使输入有效?
- python-2.7 - paramiko.ssh_exception.SSHException:没有现有会话
- html - 为什么 flexbox 容器周围有填充?
- python-3.x - 如何使用 selenium 打开网页,其中浏览器将具有此设置 --disable-web-security --user-data-dir --disable-web-security
- react-native - Expo Asset.fromModule().localUri 返回 null
- vb.net - 如何使 ComboBox 边界固定为 3D
- python - 如何为所选元素分配来自不同数据框的值
- mysql - 如何正确地将 MySQL 文本字段与任意长度的字符串进行比较?
- python - 如果通过配置管理调用 getfilesystemencoding() 会有所不同
- mysql - 基于 ID 查找最新记录的 SQL 代码帮助