Python学习-xlsx操作

一、导入库:

import pandas

pip install pandas as pd

二、操作步骤:

 当我们需要新建一个xlsx表格的时候并且列名和数据都是自定义的时候可以这样写:

    # 创建一个字典,将三个列表映射到列名
    data = {
        '二维码': data_list,
        '电子卡编号': two_data,
        '扣款金额': data_list_price
    }
    # 将字典转换为 DataFrame
    df = pd.DataFrame(data)

    # 将 DataFrame 写入 Excel 文件
    df.to_excel(file_path, index=False)

 data是为了定义列名以及需要传入表格的数据,注意,传入的数据需要是一个列表

之后将data字典转化为DataFrame格式才可以写入xlsx表格

df = pd.DataFrame(data)

转化之后可以直接调用df中的to_excel方法将文件写入xlsx表格

    df.to_excel(file_path, index=False)

三、操作已经有列名的表格

 1.读取excel表格:

  df = pd.read_excel(file_path, engine='openpyxl')

2.定义表格中要写入的数据

      new_data = pd.DataFrame({
            '手机号': pd.Series(phone_list),
            '扣款金额': pd.Series(card_price),
            '姓名': pd.Series(name_list),
            '设备名称': pd.Series(equipment_name_list)
        })

注意: pd.DataFrame是将字典转化为想入的文件,转化为DataFrame格式,至于pd.Series(phone_list),是将列表转化为 Pandas 的 Series 对象。但是实际上一般不需要用这个转化

3.追加数据

        # 将新数据追加到现有 DataFrame 中
        df = pd.concat([df, new_data], ignore_index=True)

 调用concat方法,将数据保存,df为读取的xlsx文件,new_data为需要写入的数据,

ignore_index=True,是为了避免重复索引

4.保存文件:

df.to_excel(file_path, index=False, engine='openpyxl')

保存文件file_path为文件路径 ,index=Fales是为了避免把索引也写入进表格中

engine='openpyxl'是为了帮python确定你需要操作的文件类型,Pandas 可能会使用xlsxwriterxlwt(用于 .xls文件),但openpyxl专门用于.xlsx文件。

完整代码:

def update_excel_with_phone_numbers(file_path, phone_list, name_list, card_price, equipment_name_list):
    # 确保文件路径是字符串类型,并且文件存在
    if not isinstance(file_path, str) or not os.path.isfile(file_path):
        raise ValueError("Invalid file path or buffer object type")

    # 尝试读取现有的 Excel 文件
    try:
        df = pd.read_excel(file_path, engine='openpyxl')
    except PermissionError:
        print(
            f"Permission denied: Cannot access the file at {file_path}. Make sure the file is not open in another "
            f"program and you have the necessary permissions.")
        return
    except Exception as e:
        print(f"Failed to read Excel file: {e}")
        return

    # 确保“手机号”和“扣款金额”列存在
    if '手机号' in df.columns and '扣款金额' in df.columns and '姓名' in df.columns and '设备名称' in df.columns:
        # 获取现有的行数
        existing_rows = len(df)

        # 将手机号和扣款金额列表转换为 DataFrame
        new_data = pd.DataFrame({
            '手机号': pd.Series(phone_list),
            '扣款金额': pd.Series(card_price),
            '姓名': pd.Series(name_list),
            '设备名称': pd.Series(equipment_name_list)
        })

        # 将新数据追加到现有 DataFrame 中
        df = pd.concat([df, new_data], ignore_index=True)

        # 尝试保存更新后的 Excel 文件
        try:
            df.to_excel(file_path, index=False, engine='openpyxl')
            print(f"Phone numbers and amounts have been appended to the columns '手机号' and '扣款金额' in {file_path}")
        except PermissionError:
            print(f"Permission denied: Cannot save the file at {file_path}. Make sure you have write permissions.")
        except Exception as e:
            print(f"Failed to save Excel file: {e}")
    else:
        print("The columns '手机号' and '扣款金额' do not exist in the Excel file.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值