用xlwings支持的方式规范改写这段代码:import xlwings as xw import os def main(): mould_excel_path = r'退汇模板.xlsx' ori_excel_path = r'数据源.xlsx' result_folder = './退汇表' if not os.path.exists(result_folder): os.makedirs(result_folder) app = xw.App(visible=False, add_book=False) ori_wb = app.books.open(ori_excel_path) ori_sheet = ori_wb.sheets[0] ori_sheet.calculate() # 计算公式 rows = ori_sheet.used_range.last_cell.row cols = ori_sheet.used_range.last_cell.column for r in range(2, rows + 1): info = {} mould_wb = xw.Book(mould_excel_path) mould_sheet = mould_wb.sheets[0] for c in range(1, cols + 1): if ori_sheet[c, 1].value: info[ori_sheet[c, 1].value] = ori_sheet[r, c].value print(info) mould_sheet.range('F1').value = info['日期'] mould_sheet.range('J1').value = info['凭证号'] mould_sheet.range('J3').value = info['主体\\姓名'] mould_sheet.range('J4').value = info['账户'] mould_sheet.range('J5').value = info['开户行'] mould_sheet.range('J7').value = info['支付金额'] mould_sheet.range('G9').value = info['预算文号'] mould_sheet.range('J10').value = info['款项用途'] result_file_path = os.path.join(result_folder, f"{info['文件名']}.xlsx") mould_wb.save(result_file_path) mould_wb.close() ori_wb.close() app.quit() if __name__ == '__main__': try: main() except Exception as e: input(f"error line:{e.__traceback__.tb_lineno}-{e}")
时间: 2024-04-28 20:24:16 浏览: 186
import xlwings as xw
import os
def main():
mould_excel_path = r'退汇模板.xlsx'
ori_excel_path = r'数据源.xlsx'
result_folder = './退汇表'
if not os.path.exists(result_folder):
os.makedirs(result_folder)
app = xw.App(visible=False, add_book=False)
ori_wb = app.books.open(ori_excel_path)
ori_sheet = ori_wb.sheets[0]
ori_sheet.calculate() # 计算公式
rows, cols = ori_sheet.used_range.last_cell.row, ori_sheet.used_range.last_cell.column
for r in range(2, rows + 1):
info = {}
mould_wb = xw.Book(mould_excel_path)
mould_sheet = mould_wb.sheets[0]
for c in range(1, cols + 1):
if ori_sheet[c, 1].value:
info[ori_sheet[c, 1].value] = ori_sheet[r, c].value
print(info)
mould_sheet.range('F1').value = info.get('日期', None)
mould_sheet.range('J1').value = info.get('凭证号', None)
mould_sheet.range('J3').value = info.get('主体\\姓名', None)
mould_sheet.range('J4').value = info.get('账户', None)
mould_sheet.range('J5').value = info.get('开户行', None)
mould_sheet.range('J7').value = info.get('支付金额', None)
mould_sheet.range('G9').value = info.get('预算文号', None)
mould_sheet.range('J10').value = info.get('款项用途', None)
result_file_path = os.path.join(result_folder, f"{info.get('文件名', None)}.xlsx")
mould_wb.save(result_file_path)
mould_wb.close()
ori_wb.close()
app.quit()
if __name__ == '__main__':
try:
main()
except Exception as e:
input(f"error line:{e.__traceback__.tb_lineno}-{e}")
阅读全文