truncate, copy from one xlsx and paste to another with openpyxl: messes up all text boxes, charts etc

你说的曾经没有我的故事 提交于 2019-12-10 11:43:51

问题


I try to automate some steps I have to do each week in python 3.7.3. Basically, it's all about

  • truncating xlsx-1
  • copying from xlsx-2 to the truncated xlsx-1
  • saving xlsx-1

It all goes well, but after these steps my xlsx-1 is all messed up. All formulas are still working but all the text boxes (with, and without cell referrences in them) are gone, and all charts have a different format (e.g. new borders).

Why does this happen, and what can I do to avoid these issues?

print("Please type in the date first (format: YYMMDD) > ")

last_wk = dt.date.today().isocalendar()[1] - 1
curr_wk = last_wk + 1

prefix = f"{input()}_CW{str(last_wk)}"
prefix_final = f"{input()}_CW{str(curr_wk)}"

p_basic = 'C:\\Users\\Don_Andrej\\OneDrive - Shared Services GmbH\\Profile\\Desktop\\180816_Start\\Reports'
p_export = os.path.join(p_basic, '_process_BE_NL_BRE_exports', f"{prefix}")
p_final = os.path.join(p_basic, '_process_BE_NL_BRE_exports', f"{prefix_final}")

files = ['Offline vs Online sales week', 
        'Gefactureerd week',
        'BE_onlineshopSales_oldOrder']

def truncate():
    for file in files:
        p = p_export + f"_{file}.xlsm"

        wb = opx.load_workbook(filename = p)
        ws = wb['rawData']

        for all_row in range(1, ws.max_row + 1):
            for all_col in range(1, ws.max_column + 1):
                ws.cell(row = all_row, column = all_col).value = None

        wb.save(p)
        wb.close()
        print(f"{file} has been truncated!")

def copy_paste():
    for file in files:
        p_from = p_export + f"_EXPORT_{file}.xlsx"
        p_to = p_export + f"_{file}.xlsx"

        wb_from = opx.load_workbook(filename = p_from)
        ws_from = wb_from['Sheet1']

        wb_to = opx.load_workbook(filename = p_to)
        ws_to = wb_to['rawData']


        for all_row in range(1, ws_from.max_row + 1):
            for all_col in range(1, ws_from.max_column + 1):
                ws_to.cell(row = all_row, column = all_col).value = ws_from.cell(row = all_row, column = all_col).value

        wb_to.save(p_to)
        wb_to.close()
        wb_from.close()
        print(f"The export were copied into {file}")


truncate()
copy_paste()

来源:https://stackoverflow.com/questions/56221282/truncate-copy-from-one-xlsx-and-paste-to-another-with-openpyxl-messes-up-all-t

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