简体   繁体   English

使用python覆盖excel中的工作表

[英]Overwrite a sheet in excel using python

I'm trying to overwrite one sheet of my excel file with data from a .txt file.我正在尝试用 .txt 文件中的数据覆盖我的一张 excel 文件。 The excel file I'm bringing the data into has several sheets but I only want to overwrite the 'Previous Month' sheet.我将数据带入的 excel 文件有几张表,但我只想覆盖“上个月”表。 Every time I run this code and open the excel file only the previous month sheet is there and nothing else.每次我运行此代码并打开 excel 文件时,只有上个月的工作表在那里,没有别的。 Many solutions on here show how to add more sheets, I'm trying to update an already existing sheet in an excel with 8 sheets total.此处的许多解决方案展示了如何添加更多工作表,我正在尝试更新 Excel 中已经存在的工作表,总共 8 个工作表。

How can I fix my code so that only the one sheet is edited but all of them stay there?如何修复我的代码,以便只编辑一张工作表但所有工作表都留在那里?

import pandas as pd
#importing previous month data#
writer = pd.ExcelWriter('file.xlsx')
df = pd.read_csv('file.txt', sep='\t')
df.to_excel(writer, sheet_name='Previous Month', startrow=4, startcol=2)
writer.save()
writer.close()

Edited code- whatever is happening here keeps corrupting my original file编辑后的代码 - 这里发生的任何事情都会破坏我的原始文件

import pandas as pd 
import openpyxl
#importing previous month data#
writer=  pd.ExcelWriter('file.xlsx', mode= 'a', engine="openpyxl", if_sheet_exists="replace")
df = pd.read_csv('file.txt', sep='\t')
df.to_excel(writer, sheet_name="Previous Month", startrow=2, startcol=4) 
writer.save()
writer.close()

You can use openpyxl.load_workbook() to do what you are looking for.你可以使用openpyxl.load_workbook()来做你正在寻找的东西。 While I did try the above suggestions, it didn't work for me.虽然我确实尝试了上述建议,但它对我不起作用。 the load_workbook() usually runs without issues. load_workbook()通常运行没有问题。 So, hope this works for you as well.所以,希望这也适用于你。 I open the output file using load_workbook() , deleted the existing sheet ( Sheet2 here) if it exists, then create and write the data using create_sheet() and dataframe_to_rows ( Ref ).我使用load_workbook()打开输出文件,如果存在则删除现有工作表(此处为Sheet2 ),然后使用create_sheet()dataframe_to_rows ( Ref ) 创建和写入数据。 Let me know in case of questions/issues.如果有问题/问题,请告诉我。

import pandas as pd 
import openpyxl

df = pd.read_csv('file.txt', sep='\t')

wb=openpyxl.load_workbook('output.xlsx')  # Open workbook
if "Sheet2" in wb.sheetnames:  # If sheet exists, delete it
    del wb['Sheet2']

ws = wb.create_sheet(title='Sheet2')  # Create new sheet

from openpyxl.utils.dataframe import dataframe_to_rows
rows = dataframe_to_rows(df, index=False, header=True) # Write dataframe as rows

for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
         ws.cell(row=r_idx+2, column=c_idx+4, value=value) #Add... the 2, 4 are the offset, similar to the startrow and startcol in your code
            
wb.save('output.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM