简体   繁体   English

Python:反复写入Excel文件

[英]Python: Iteratively Writing to Excel Files

Python 2.7. Python 2.7。 I'm using xlsxwriter. 我正在使用xlsxwriter。

Let's say I have myDict = {1: 'One', 2: 'Two', 3: 'Three'} 假设我有myDict = {1: 'One', 2: 'Two', 3: 'Three'}

I need to perform some transformation on the value and write the result to a spreadsheet. 我需要对值进行一些转换,然后将结果写入电子表格。

So I write a function to create a new file and put some headers in there and do formatting, but don't close it so I can write further with my next function. 因此,我编写了一个函数来创建一个新文件,并在其中放置一些标头并进行格式化,但是请不要关闭它,以便我可以使用下一个函数进一步编写。

Then I write another function for transforming my dict values and writing them to the worksheet. 然后,我编写了另一个函数来转换dict值并将它们写入工作表。

I'm a noob when it comes to classes so please forgive me if this looks silly. 我上课时是个菜鸟,所以如果这看起来很傻,请原谅我。

import xlsxwriter

class ReadWriteSpreadsheet(object):
    def __init__(self, outputFile=None, writeWorkbook=None,     writeWorksheet=None):
        self.outputFile = outputFile
        self.writeWorksheet = writeWorksheet
        self.writeWorkbook = writeWorkbook

    # This function works fine
    def setup_new_spreadsheet(self):
        self.writeWorkbook = xlsxwriter.Workbook(self.outputFile)
        self.writeWorksheet = self.writeWorkbook.add_worksheet('My Worksheet')
        self.writeWorksheet.write('A1', 'TEST') 

    # This one does not
    def write_data(self):
        # Forget iterating through the dict for now
        self.writeWorksheet.write('A5', myDict[1])

x = ReadWriteSpreadsheet(outputFile='test.xlsx')
x.setup_new_spreadsheet()
x.write_data()

I get: 我得到:

Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x00000000023FDF28>> ignored

The docs say this error is due to not closing the workbook, but if I close it then I can't write to it further... 文档说此错误是由于未关闭工作簿引起的,但是如果我关闭工作簿,则无法进一步写信...

How do I structure this class so that the workbook and worksheet from setup_new_spreadsheet() is able to be written to by write_data() ? 如何构造此类,以便write_data()可以写入setup_new_spreadsheet()中的工作簿和工作表?

When you do ReadWriteSpreadsheet() you get a new instance of the class you've defined. 当您执行ReadWriteSpreadsheet()您将获得一个已定义的类的新实例 That new instance doesn't have any knowledge of any workbooks that were set up in a different instance. 该新实例不了解在不同实例中设置的任何工作簿。

It looks like what you want to do is get a single instance, and then issue the methods on that one instance: 看起来您想要做的是获得一个实例,然后在该实例上发出方法:

x = ReadWriteSpreadsheet(outputFile='test.xlsx')
x.setup_new_spreadsheet()
x.write_data()

To address your new concern: 要解决您的新问题:

The docs say this error is due to not closing the workbook, but if I close it then I can't write to it further... 文档说此错误是由于未关闭工作簿引起的,但是如果我关闭工作簿,则无法进一步写信...

Yes, that's true, you can't write to it further. 是的,的确如此,您无法再对其进行写操作。 That is one of the fundamental properties of Excel files. 这是Excel文件的基本属性之一。 At the level we're working with here, there's no such thing as "appending" or "updating" an Excel file. 在我们正在使用的级别上,没有诸如“附加”或“更新” Excel文件之类的东西。 Even the Excel program itself cannot do it. 甚至Excel程序本身也无法做到这一点。 You only have two viable approaches: 您只有两种可行的方法:

  1. Keep all data in memory and only commit to disk at the very end. 将所有数据保留在内存中,最后只提交到磁盘。
  2. Reopen the file, reading the data into memory; 重新打开文件,将数据读入内存; modify the in-memory data; 修改内存中的数据; and write all the in-memory data back out to a new disk file (which can have the same name as the original if you want to overwrite). 并将所有内存中的数据写回到新的磁盘文件中(如果要覆盖,可以与原始文件具有相同的名称)。

The second approach requires using a package that can read Excel files. 第二种方法要求使用可以读取Excel文件的软件包。 The main choices there are xlrd and OpenPyXL . 主要选择是xlrdOpenPyXL The latter will handle both reading and writing, so if you use that one, you don't need XlsxWriter . 后者将同时处理阅读和写作,因此,如果您使用它,则不需要XlsxWriter

The exception mentioned in your question is triggered when python realises you will not need to use your Workbook any more in the rest of your code and therefore decides to delete it from his memory (garbage collection). 当python意识到您将不再需要在其余代码中使用工作簿并因此决定从他的内存(垃圾回收)中删除该工作簿时,就会触发问题中提到的异常。 When doing so, it will realise you haven't closed your workbook yet and so will not have persisted your excel spreadsheet at all on the disk (only happen on close I assume) and will raise that exception. 这样做时,它将意识到您尚未关闭工作簿,因此不会将excel电子表格完全保留在磁盘上(我假设仅在关闭时发生),并将引发该异常。

If you had another method close on your class that did: self.writeWorkbook.close() and made sure to call it last you would not have that error. 如果您的类上有另一个关闭方法:self.writeWorkbook.close()并确保最后调用它,则不会出现该错误。

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

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