我正在使用Amazon的product-listing-creation模板在Amazon上创建和更新产品列表。 Amazon的模板包括用于将CSV内容导入模板的Excel宏,但我希望绕过此步骤并直接克隆,编辑和重新保存Excel文件。
我有openpyxl代码,用于打开模板,填写单元格并保存带有已填充信息的新副本。为了允许openpyxl读取文件,我必须编辑Amazon提供的模板。我已将每张工作表从原始.xlsm模板复制到空白工作簿中,并将其另存为.xlsx。除了我将在一分钟内详细介绍的错误之外,该文件仍然可以由Amazon处理,因此我不认为应该(完全)责怪格式更改。
这是写输出文件的代码:
def create_workbook(chunk, file_count):
'''This creates a single output workbook from a chunk of campaign_dicts.'''
workbook = openpyxl.load_workbook(AMAZON_TEMPLATE_FILENAME)
sheet = workbook["Template"]
rows = []
for campaign_dict in chunk:
rows += create_rows(campaign_dict) # Returns a list of lists of cell values.
write_rows_to_sheet(sheet, rows, TEMPLATE_DATA_STARTING_ROW, TEMPLATE_DATA_STARTING_COL)
workbook.save("output/output" + str(file_count) + ".xlsx")
def write_rows_to_sheet(sheet, rows, starting_row, starting_col):
'''This writes data to a worksheet of an openpyxl workbook, starting from the given coordinates.
The rows for this function should be a list of lists, where each list is a row.'''
for row_number, row in enumerate(rows):
for column_number, cell in enumerate(row):
if isinstance(cell, str):
cell = re.sub(ILLEGAL_CHARACTERS_RE, '', cell)
sheet.cell(row = row_number + starting_row + 1, column = column_number + starting_col + 1).value = cell
return sheet
问题是,当我尝试将此代码生成的任何文件上传到Amazon进行处理时,它会被以下处理报告拒绝:
Feed Processing Summary:
Number of records processed 0
Number of records successful 0
original-record-number sku error-code error-type error-message
0 99217 Info The processing report is too long, or has generated too many errors for it to display properly in the Excel sheet. So we have generated the processing report in Text format. The Excel reports are limited to 50,000 errors and 1,000,000 rows of product data.
0 90502 Fatal The file does not contain a worksheet with a template type that is supported for Excel upload. Please save your file in a tab-delimited text file format (*.txt) and upload again.
我发现一种解决方法是在Excel中打开输出文件并立即保存它,而无需对该文件或其数据进行任何更改。我无法发布实际的文件之前和之后(专有信息),但是我知道文件在重新保存之前和之后肯定会发生更改,尽管在保存文件时我没有进行任何更改。这只是开-关-关。请注意,当我打开并重新保存文件时,Excel不会抱怨文件的内容。
是什么原因导致这种情况发生,以及如何在代码中对其进行修复,以使我没有此中间步骤?