将 .txt 导入现有 excel 到新工作表
Import .txt into existing excel into new worksheet
我完全沉浸在我正在进行的小项目中。
我每月一次将数据从 .txt 文件导入现有的 excel。每次执行此操作时,我都想在 excel 中创建一个新工作表并将数据添加到其中,而不更改其他工作表中的任何内容。我的方法看起来像这样。
from datetime import date, timedelta
import pandas as pd
import numpy as np
import openpyxl
from openpyxl import load_workbook
import os
now = date.today()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
if last_month != 1:
filename = "0" + str(last_month) + "." + str(now.year) + ".txt"
else:
filename = "12" + "." + str(last_year) + ".txt"
print(filename)
writer = pd.ExcelWriter("Ausgabenliste.xlsx", engine='openpyxl')
if os.path.exists("Ausgabenliste.xlsx"):
book = openpyxl.load_workbook("Ausgabenliste.xlsx")
writer.book = book
df = pd.read_csv(filename, sep=" ")
df.to_excel(writer, sheet_name=filename)
writer.save()
writer.close()
我总是收到以下错误消息:
感谢您的帮助。非常感谢。
这会向现有 XLSX 添加一个新工作表:
# Load existing
book = load_workbook('x.xlsx')
writer = pd.ExcelWriter('x.xlsx', engine = 'openpyxl')
# Starting with the existing worksheets
writer.book = book
# Adding a new worksheet
df.to_excel(writer, sheet_name='gtomer')
writer.save()
我完全沉浸在我正在进行的小项目中。 我每月一次将数据从 .txt 文件导入现有的 excel。每次执行此操作时,我都想在 excel 中创建一个新工作表并将数据添加到其中,而不更改其他工作表中的任何内容。我的方法看起来像这样。
from datetime import date, timedelta
import pandas as pd
import numpy as np
import openpyxl
from openpyxl import load_workbook
import os
now = date.today()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
if last_month != 1:
filename = "0" + str(last_month) + "." + str(now.year) + ".txt"
else:
filename = "12" + "." + str(last_year) + ".txt"
print(filename)
writer = pd.ExcelWriter("Ausgabenliste.xlsx", engine='openpyxl')
if os.path.exists("Ausgabenliste.xlsx"):
book = openpyxl.load_workbook("Ausgabenliste.xlsx")
writer.book = book
df = pd.read_csv(filename, sep=" ")
df.to_excel(writer, sheet_name=filename)
writer.save()
writer.close()
我总是收到以下错误消息:
感谢您的帮助。非常感谢。
这会向现有 XLSX 添加一个新工作表:
# Load existing
book = load_workbook('x.xlsx')
writer = pd.ExcelWriter('x.xlsx', engine = 'openpyxl')
# Starting with the existing worksheets
writer.book = book
# Adding a new worksheet
df.to_excel(writer, sheet_name='gtomer')
writer.save()