python 将数据写入excel

目的:将数据追加进excel

def writeExcel(list, save_path,excel_header,excel_sheet_name):
    """
    write to excel
    需要导入的库:
        from openpyxl import Workbook
        from openpyxl import load_workbook
    :param list:
    :param save_path:
    :excel_header:
    :excel_sheet_name:
    :return:
    """

    # 判断是否已经存在excel
    if os.path.isfile(save_path):
        wb = load_workbook(save_path) # 打开excel
        ws = wb[excel_sheet_name] # 选择sheet
        for row in list: # 开始追加数据
            # print(row)
            ws.append(row)
            # print(row)
        wb.save(save_path)
    else:
        wb = Workbook()  # 创建一个workbook(工作簿)
        ws = wb['Sheet'];  # 得到名称为"sheet"的工作表
        ws.title = excel_sheet_name  # 将"sheet"改名为excel_sheet_name
        ws.append(excel_header) #创建表头
        # print(list)
        for row in list:
            # print(row)
            ws.append(row)
            # print(row)
        wb.save(save_path)

 

posted @ 2021-03-24 17:54  SirPi  阅读(691)  评论(0编辑  收藏  举报