相关疑难解决方法(0)

如何写入现有的excel文件而不覆盖数据(使用pandas)?

我使用pandas以下列方式写入excel文件:

import pandas

writer = pandas.ExcelWriter('Masterfile.xlsx') 

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
Run Code Online (Sandbox Code Playgroud)

Masterfile.xlsx已包含许多不同的选项卡.

Pandas正确写入"Main"表,不幸的是它还删除了所有其他选项卡.

python excel python-2.7 pandas

105
推荐指数
7
解决办法
12万
查看次数

使用python pandas使用新数据框附加现有excel表

我目前有这个代码.它完美地运作.

它循环遍历文件夹中的excel文件,删除前两行,然后将它们保存为单独的excel文件,并将文件作为附加文件保存在循环中.

目前,每次运行代码时附加的文件都会覆盖现有文件.

我需要将新数据附加到已经存在的Excel工作表的底部('master_data.xlsx)

dfList = []
path = 'C:\\Test\\TestRawFile' 
newpath = 'C:\\Path\\To\\New\\Folder'

for fn in os.listdir(path): 
  # Absolute file path
  file = os.path.join(path, fn)
  if os.path.isfile(file): 
    # Import the excel file and call it xlsx_file 
    xlsx_file = pd.ExcelFile(file) 
    # View the excel files sheet names 
    xlsx_file.sheet_names 
    # Load the xlsx files Data sheet as a dataframe 
    df = xlsx_file.parse('Sheet1',header= None) 
    df_NoHeader = df[2:] 
    data = df_NoHeader 
    # Save individual dataframe
    data.to_excel(os.path.join(newpath, fn))

    dfList.append(data) 

appended_data = …
Run Code Online (Sandbox Code Playgroud)

python excel for-loop append pandas

17
推荐指数
4
解决办法
4万
查看次数

合法 .xlsx 文件上的 openpyxl load_workbook() 会导致 zipfile.BadZipFile 错误

我想做的是将数据帧数据附加到现有的合法 Excel 文件中。我使用了 openpyxl 中的 load_workbook() 函数,但它系统地返回错误。这是一些在我的机器上崩溃的代码:

from openpyxl import load_workbook

report_path = root_folder + '\\log_report.xlsx'
writer = pd.ExcelWriter(report_path, engine='openpyxl')
writer.book = load_workbook(report_path)
writer.close()
Run Code Online (Sandbox Code Playgroud)

这里,log_report.xlsx已经存在并且是通过pandas .to_excel()创建的。在使用 openpyxl load_workbook() 打开之前,可以打开它、编辑它并执行 MS Excel 允许的任何操作。我收到以下错误返回:

Traceback (most recent call last):
  File "D:/failsafe_counter/main.py", line 419, in <module>
    writer.book = load_workbook(report_path)
  File "D:\failsafe_counter\venv\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "D:\failsafe_counter\venv\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "D:\failsafe_counter\venv\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:\Users\XXXX\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1269, …
Run Code Online (Sandbox Code Playgroud)

python excel openpyxl

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

excel ×3

python ×3

pandas ×2

append ×1

for-loop ×1

openpyxl ×1

python-2.7 ×1