简体   繁体   English

Python - Excel - 将工作表添加到现有工作簿而不删除工作表

[英]Python - Excel - Add sheet to existing workbook without removing sheets

Context: I am attempting to automate a report that is rather complicated (not conceptually, just in the sheer volume of things to keep track of).上下文:我试图自动化一个相当复杂的报告(不是概念上的,只是为了跟踪大量的事情)。 The method I settled on after a lot of investigation was to;经过大量调查,我确定的方法是;

  1. Create a template xlsx file which has a couple summary pages containing formulas pointing at other (raw data) sheets within the file.创建一个模板 xlsx 文件,其中有几个摘要页面,其中包含指向文件中其他(原始数据)工作表的公式。
  2. Pull data from SQL Server and insert into template file, overwriting the raw data sheet with relevant data.从 SQL Server 中提取数据并插入模板文件,用相关数据覆盖原始数据表。
  3. Publish report (Most likely this will just be moving xlsx file to a new directory).发布报告(很可能这只是将 xlsx 文件移动到新目录)。

Obviously, I have spent a lot of time looking at other peoples solutions to this issue (as this topic has been discussed a lot).显然,我花了很多时间查看其他人对这个问题的解决方案(因为这个话题已经讨论了很多)。 The issue I have found however is that (at least in my search) none of the methods purposed have worked for me, my belief is that the previously correct responses are no longer relevant in current versions of pandas etc. Rather than linking to the dozens of articles attempting to answer this question, I will explain the issues I have had with various solutions.然而,我发现的问题是(至少在我的搜索中)没有一种方法对我有用,我相信以前正确的响应在当前版本的熊猫等中不再相关。而不是链接到几十个在试图回答这个问题的文章中,我将解释我在各种解决方案中遇到的问题。

  1. Using openpyxl instead of xlsxwriter - This resulted in "BadZipFile: File is not a zip file" response.使用 openpyxl 而不是 xlsxwriter - 这导致“BadZipFile: File is not a zip file”响应。 Which as I understand pertains to the pandas version, or rather the fix (mode='a') does not work due to the pandas version (I believe anything beyond 1.2 has this issue).据我所知,这与 Pandas 版本有关,或者更确切地说,由于 Pandas 版本,修复 (mode='a') 不起作用(我相信 1.2 以外的任何东西都有这个问题)。
  2. Helper Function This does not work however, also throws the BadZipFile error. Helper Function但是这不起作用,还会引发 BadZipFile 错误。

Below is a heavily redacted version of the code which should give all the required detail.下面是代码的大量编辑版本,它应该提供所有必需的细节。

#Imports
import os
import pyodbc
import numpy as np
import shutil
import pandas as pd
import datetime
from datetime import date
from openpyxl import load_workbook


# Set database connection variables.
cnxn = pyodbc.connect(*Credentials*)
cursor = cnxn.cursor()

df = pd.read_sql_query(script, cnxn)
df.to_excel(writer, sheet_name = 'Some Sheet',index=False)

writer.close()

Long story short here, I am finding it very frustrating that what should be very very simple is turning into a multiple day long exercise.长话短说,我觉得非常令人沮丧的是,本来应该非常非常简单的事情却变成了为期多天的练习。 Please if anyone has experience with this and could offer some insight I would be very grateful.请如果有人有这方面的经验并能提供一些见解,我将不胜感激。

Finally, I have to admit that I am quite new to using python, though I have not found the transition too difficult until today.最后,我不得不承认我对使用 python 还很陌生,尽管直到今天我才发现过渡太困难。 Most of the issues I have been having are easily solvable (for me), with the exception of this issue.我遇到的大多数问题都很容易解决(对我来说),除了这个问题。 If there is something I have somehow completely missed, put me on the track and I will not be a bother.如果有什么我完全错过了,把我放在赛道上,我就不会打扰了。

Okay, so I found that I was infact incorrect (big surprise).好的,所以我发现我实际上是不正确的(大惊喜)。 That is, my statement that the helper function does not work.也就是说,我说辅助函数不起作用。 It does work, the ZipFile issue was most likely caused by some form of protection on the workbook.它确实有效,ZipFile 问题很可能是由工作簿上的某种形式的保护引起的。 Funny thing is, I was able to get it working with a new workbook, but when I changed the name of the new workbook it again started throwing the ZipFile error.有趣的是,我能够让它与新工作簿一起工作,但是当我更改新工作簿的名称时,它再次开始抛出 ZipFile 错误。 After awhile of creating new files and trying different things I eventually got it to work.在创建新文件并尝试不同的事情一段时间后,我最终让它工作了。

Two things I would note about the helper function;关于辅助函数,我要注意两件事;

  1. It is not particularly efficient.它不是特别有效。 At least not in the way I have set it up.至少不是我设置的方式。 I replaced all instances of 'to_excel' with 'append_df_to_excel' from the helper function.我用辅助函数中的“append_df_to_excel”替换了“to_excel”的所有实例。 Doing this resulted in run time going from about 1-2 minutes to well over 10. I will do some more testing and see why this might be (I will post back if I find something intersting), but just something to watch for if using larger datasets.这样做会导致运行时间从大约 1-2 分钟到超过 10 分钟。我会做更多的测试,看看为什么会这样(如果我发现一些有趣的东西,我会回帖),但如果使用更大的数据集。
  2. Not an issue as such, but for me to get this to work as expected, I had to alter the function slightly.不是这样的问题,但为了让我按预期工作,我不得不稍微改变函数。 Specifically, in order to use the truncate feature in my situation, I needed to move the 'truncate' section to be above the 'firstrow' section.具体来说,为了在我的情况下使用截断功能,我需要将“截断”部分移到“第一行”部分的上方。 In my situation it made more sense to do that, rather than to specify the start row prior to truncating the sheet.在我的情况下,这样做更有意义,而不是在截断工作表之前指定起始行。

Hope this helps anyone running into the same issue.希望这可以帮助任何遇到相同问题的人。

Lesson learned, as always the information is out there, its just a matter of actually paying close attention and trying things out rather than copy paste and scratching your head when things aren't working.吸取的教训,一如既往,信息就在那里,这只是一个实际密切关注和尝试的问题,而不是在事情不工作时复制粘贴和挠头。

暂无
暂无

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

相关问题 在python中将新工作表添加到现有工作簿 - Add a new sheet to a existing workbook in python python:将数据框更新到现有的excel工作表,而不会覆盖同一工作表和其他工作表上的内容 - python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets 将工作簿中的多个 Excel 工作表合并为一张工作表 Python - Combine Multiple Excel sheets within Workbook into one sheet Python 如何使用python将数据从一个工作表添加到另一个工作簿中的现有工作表而不覆盖其他工作表的数据? - How to add data using python from one sheet to an existing sheet in another workbook without overwriting other sheet's data? 如何 append 列出 python 中现有 excel 工作簿(同一张表)的列表 - How to append a list to an existing excel workbook (same sheet) in python 用python加密excel工作簿表 - encrypting excel workbook sheet with python 如何使用 python 将 excel 工作簿中的内容复制到另一个工作簿而不丢失 excel 格式 - How to copy contents from a sheet of an excel workbook to another workbook without loosing the excel formatting using python 使用熊猫,如何只从 Excel 工作簿中读取一张工作表而不加载任何其他工作表? - Using pandas, how to only read one sheet from Excel workbook without loading any of the other sheets? 使用python将文本文件添加到现有Excel工作簿 - Using python to add a text file to existing Excel Workbook PYTHON:如何将列添加到具有多个工作表的Excel工作表 - PYTHON: How to add a column to Excel Sheet with multiple Sheets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM