无法保存在 xlsx 文件中所做的修改

Cannot save modifications made in xlsx file

我读取了一个 .xlsx 文件,更新了它,但我无法保存它

from xml.dom import minidom as md
        [... some code ....]
        sheet = workDir + '/xl/worksheets/sheet'
        sheet1 = sheet + '1.xml'
        importSheet1 = open(sheet1,'r')
        whole_file= importSheet1.read()
        data_Sheet = md.parseString(whole_file)
        [... some code ....]
            self.array_mem_name = []
            y = 1
            x = 5 #first useful row
            day = int(day)
            found = 0
            while x <= len_array_shared:
                readrow = data_Sheet.getElementsByTagName('row')[x]
                c_data = readrow.getElementsByTagName('c')[0]
                c_attrib = c_data.getAttribute('t')
                if c_attrib == 's':
                    vName = c_data.getElementsByTagName('v')[0].firstChild.nodeValue
                    #if int(vName) != broken:
                    mem_name = self.array_shared[int(vName)]
                    if mem_name != '-----':
                        if mem_name == old:
                            c_data = readrow.getElementsByTagName('c')[day]
                            c_attrib = c_data.getAttribute('t')
                            if (c_attrib == 's'):
                                v_Attrib = c_data.getElementsByTagName('v')[0].firstChild.nodeValue
                                if v_Attrib != '':
                                    #loc = self.array_shared[int(v_Attrib)]
                                    index = self.array_shared.index('--')
                                    c_data.getElementsByTagName('v')[0].firstChild.nodeValue = index
    
                                    with open(sheet1, 'w') as f:
                                        f.write(whole_file)

如您所见,我使用 f.write(whole_file),但 whole_file 没有使用 index 所做的更改。 检查调试我看到新值已添加到节点,但我无法使用修改后的值保存 sheet1

我改为使用 openpyxl,正如 中所建议的那样。我发现这个工具更适合我的工作。使用 openpyxl,读取单元格值比使用 xml.dom.minidom.

容易得多

我唯一担心的是 openpyxl 加载工作簿似乎真的比 dom 慢。也许内存过载了。但是,我对使用比这个小性能问题更简单的东西更感兴趣。