У меня проблема при попытке сохранить книгу Excel с комментариями.Без каких-либо комментариев в файле Excel, нет никаких проблем с моими сценариями.Я просто использую:
wb_archive = load_workbook(archive_file)
Однако, если файл, который я хочу сохранить, имеет комментарии, он не работает, и у меня появляется сообщение:
AttributeError: 'NoneType'У объекта нет атрибута «чтение»
Итак, я открываю файл с помощью метода:
wb_archive = load_workbook(archive_file, keep_vba=True)
Первый запуск в порядке, однако второй всегда завершается ошибкой с ошибкой:
KeyError: «В архиве нет элемента с именем 'xl / sharedStrings.xml'"
Я где-то ошибся в своем коде?
# coding: utf8
# !/usr/bin/env python3
"""
Program to extract Excel data to an archive
Program Python version 3.5
"""
# Standard Library
from pathlib import Path
from datetime import date
# External Libraries
from openpyxl import load_workbook
# Import the interface
# Import the project .py files
filein = "file1.xlsx"
fileout = "file2.xlsx"
def xlarchive(source_file, source_sheet, archive_file, archive_sheet, source_start_line=0, archiving_method="NEW", option_date=False):
"""
Function to save data from an Excel Workbook (source) to another one (archive).
Variables shall be check before calling the function.
:param source_file: file where data are copied from (source)
:type source_file: Path file
:param source_sheet: name of the sheet where data are located on the source file
:type source_sheet: string
:param archive_file: file where data are copied to (destination)
:type archive_file: Path file
:param archive_sheet: name of the sheet where data have to be copied on the destination file
:type archive_sheet: string
:param source_start_line:
:type source_start_line: int
:param archiving_method: defines if the destination file has to be created
:type archiving_method: string
:param option_date: defines if the extraction data shall be recorded
:type option_date: bool
:return: None
"""
wb_source = load_workbook(source_file)
#keep_vba = true to avoid issue with comments
ws_source = wb_source.get_sheet_by_name(source_sheet)
wb_archive = load_workbook(archive_file)
ws_archive = wb_archive.get_sheet_by_name(archive_sheet)
if archiving_method == "NEW":
# index of [archive_sheet] sheet
idx = wb_archive.sheetnames.index(archive_sheet)
# remove [ws_archive]
wb_archive.remove(ws_archive)
# create an empty sheet [ws_archive] using old index
wb_archive.create_sheet(archive_sheet, idx)
ws_archive = wb_archive.get_sheet_by_name(archive_sheet)
# If extraction has been performed the same day, previous data will be replaced
# Date are store in Excel under format YYYY-MM-DD HH:MM:SS.
# extractiondate is from datetime.now().date() and its format is YYYY-MM-DD
# Comparison thanks to string is needed
# As Openpyxl does not enable to delete row, the below code clear data and find the first empty occurrence
if option_date == True:
j = 0
for i in range(ws_archive.max_row, 1, -1):
if str(ws_archive.cell(row=i, column=1).value)[0:10] == str(date.today()):
j=j+1
ws_archive.delete_rows(ws_archive.max_row - j + 1, j)
for row in ws_source.iter_rows(min_row=source_start_line):
complete_row = []
for item in row:
complete_row.append(item.value)
if option_date is True:
complete_row.insert(0, str(date.today()))
ws_archive.append(complete_row)
wb_archive.save(archive_file)
xlarchive(filein, "Sheet1", fileout, "Sheet1", option_date=True, archiving_method="False", source_start_line=2)