保存工作簿导致OpenPyXL错误:已存在具有相同名称和范围的DefinedName

时间:2016-08-31 12:00:04

标签: python excel xlsx openpyxl

我希望在Python中使用OpenPyXL在Excel-XLSX文件中编辑一个单元格,然后将此更改的文件保存到带有其他名称的xlsx中。 但是我收到以下错误: 回溯(最近一次调用最后一次):

 File "E:\ExcelPythonTest\workspace\ExcelTest\ExcelTest.py", line 14, in <module>
    book.save(path2)
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\workbook\workbook.py", line 294, in save
    save_workbook(self, filename)
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\writer\excel.py", line 270, in save_workbook
    writer.save(filename)
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\writer\excel.py", line 251, in save
    self.write_data()
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\writer\excel.py", line 94, in write_data
    archive.writestr(ARC_WORKBOOK, write_workbook(self.workbook))
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\writer\workbook.py", line 121, in write_workbook
    defined_names.append(name)
  File "C:\Python27\lib\site-packages\openpyxl-2.4.0b1-py2.7.egg\openpyxl\workbook\defined_name.py", line 191, in append
    raise ValueError("""DefinedName with the same name and scope already exists""")
ValueError: DefinedName with the same name and scope already exists

我的代码:

import os
import openpyxl

# Change this to suit
path = r'E:\ExcelPythonTest\example.xlsx'
path2 = r'E:\ExcelPythonTest\examle_UHAHAHAHAHHA.xlsx'

book = openpyxl.load_workbook( path )
sheet = book.get_sheet_by_name('Dictionary')
print sheet['G8'].value
sheet['G8'] =  3.18
print sheet['G8'].value

book.save(path2)

任何人都可以帮助我吗?

P.S:我试图用C和c库libxl中的代码编辑相同的.xlsx。所以我认为xlsx文件没有问题。

我在没有编辑xlsx的情况下尝试了以下代码:

import os
import openpyxl

# Change this to suit
path = r'E:\ExcelPythonTest\Dt_RECORD_SHPS_RM_ROStruct.xlsx'
path2 = r'E:\ExcelPythonTest\Dt_RECORD_SHPS_RM_ROStruct_UHAHAHAHAHHA.xlsx'

book = openpyxl.load_workbook( path )

book.save(path2)

但是发生了同样的错误。

1 个答案:

答案 0 :(得分:1)

我在工作中遇到了同样的问题,直到找到解决方案。您只需要在现有代码中添加一行即可。我不完全知道defineName对象有什么用,但是生成的文件没有损坏(与没有该行不同),并且似乎没有因清除defineNames列表而引起的视觉差异。

import os
import openpyxl

# Change this to suit
path = r'E:\ExcelPythonTest\example.xlsx'
path2 = r'E:\ExcelPythonTest\examle_UHAHAHAHAHHA.xlsx'

book = openpyxl.load_workbook( path )
sheet = book.get_sheet_by_name('Dictionary')
print sheet['G8'].value
sheet['G8'] =  3.18
print sheet['G8'].value

# This fixes it   
book.defined_names.definedName = []

book.save(path2)