pandas: Writing to an existing excel file (xlsx) using to_excel

感情迁移 提交于 2019-12-05 16:40:21

When you load your workbook with use_iterators=True, it then _set_optimized_read() on the Workbook object, which cause it to be loaded read-only.

Thus, with the following code :

from openpyxl.reader.excel import load_workbook

book = load_workbook('t.xlsx', use_iterators=False) # Assume t.xlsx contains ['Data', 'Feuil2', 'Feuil3']
print book.get_sheet_names()


class temp_excel_writer():
    def __init__(self, path, book):
        self.book=book
        test_sheet=self.book.create_sheet(title='Test') # No exception here now
        self.book.save(path)
        self.use_xlsx = True
        self.sheet_names=self.book.get_sheet_names()
        print self.sheet_names
        self.actual_sheets=self.book.worksheets
        self.sheets={}
        for i,j in enumerate(self.sheet_names):
            self.sheets[j] = (self.actual_sheets[i],1)
        self.cur_sheet = None
        self.path = path # I had to modify this line also

my_temp_writer = temp_excel_writer('my_excel_file.xlsx', book)

It create a file named my_excel_file.xlsx and the following output :

 ['Data', 'Feuil2', 'Feuil3']
 ['Data', 'Feuil2', 'Feuil3', 'Test']

Hope it helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!