python中表格的读写操作

import openpyxl


def create_to_excel(wbname, data, sheetname='Sheet1', ):
    """
    将制定的信息保存到新建的excel表格中;

    :param wbname:
    :param data: 往excel中存储的数据;
    :param sheetname:
    :return:
    """

    print("正在创建excel表格%s......" % (wbname))

    # wb = openpyxl.load_workbook(wbname)

    #  如果文件不存在, 自己实例化一个WorkBook的对象;
    wb = openpyxl.Workbook()

    # 获取当前活动工作表的对象
    sheet = wb.active

    # 修改工作表的名称
    sheet.title = sheetname

    # 将数据data写入excel表格中;
    print("正在写入数据........")
    for row, item in enumerate(data):  # data发现有4行数据, item里面有三列数据;
        for column, cellValue in enumerate(item):
            cell = sheet.cell(row=row + 1, column=column + 1, value=cellValue)
            # cell = sheet.cell(row=row+1, column=column + 1)
            # cell.value = cellValue

    wb.save(wbname)
    print("保存工作薄%s成功......." % (wbname))


def readwb(wbname, sheetname=None):
    # 1. 加载工作薄
    wb = openpyxl.load_workbook(filename=wbname)

    # 2. 选择操作的工作表
    if not sheetname:
        sheet = wb.active
    else:
        sheet = wb[sheetname]

    #  读取数据, 存储为python的数据结构
    goodsInfo = []
    for row in sheet.rows:
        rowValues = [cell.value for cell in row]
        goodsInfo.append(rowValues)
    return goodsInfo


if __name__ == '__main__':
    data = [
        ['书记名称', '数量', '价格'],
        ['python核心编程', 60, 90],
        ['Java核心编程', 50, 120],
        ['Php核心编程', 100, 80],
    ]

    print("1. " + "*" * 50)
    create_to_excel('doc/excel01.xlsx', data, '书籍信息统计')

    goodsInfo = readwb('doc/excel01.xlsx', '书籍信息统计')
    # print(goodsInfo)

    print("2. " + "*" * 50)
    # 按照商品数量进行排序 sorted()
    # ['书记名称', '数量', '价格'] + [['python核心编程', 60, 90],
    #                         ['Java核心编程', 50, 120],
    #                         ['Php核心编程', 100, 80], ]

    # [
    # ['书记名称', '数量', '价格'],
    #  ['python核心编程', 60, 90],
    #  ['Java核心编程', 50, 120],
    #  ['Php核心编程', 100, 80],
    #
    #
    # ]
    numSortInfo = [goodsInfo[0]]+  sorted(goodsInfo[1:], key=lambda x: x[1])
    print(numSortInfo)
    create_to_excel('doc/sorted_by_num.xlsx', numSortInfo, '书籍信息统计按照数量排序')

    print("3. " + "*" * 50)
    #  按照商品价格进行排序 sorted()
    priceSortInfo = [goodsInfo[0]] + sorted(goodsInfo[1:], key=lambda x: x[1])
    print(priceSortInfo)
    create_to_excel('doc/sorted_by_price.xlsx', numSortInfo, '书籍信息统计按照价格排序')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Python 表格文件读写操作的封装代码示例: ```python import pandas as pd # 读取表格文件 def read_table_file(file_path): try: # 使用 pandas 库读取表格文件 data = pd.read_csv(file_path) return data except FileNotFoundError: print(f"File {file_path} not found.") return None # 写入表格文件 def write_table_file(data, file_path): try: # 将数据写入到表格文件 data.to_csv(file_path, index=False) print(f"File {file_path} saved successfully.") except: print(f"Failed to save file {file_path}.") # 测试代码 if __name__ == "__main__": # 读取表格文件 data = read_table_file("example.csv") if data is not None: print(data) # 写入表格文件 new_data = {"Name": ["John", "Mary", "Peter"], "Age": [30, 25, 40]} df = pd.DataFrame(new_data) write_table_file(df, "new_example.csv") ``` 在这个示例,我们使用了 pandas 库来读取和写入表格文件。`read_table_file` 函数接收一个文件路径作为参数,尝试读取这个文件并返回一个 pandas 的 DataFrame 对象。`write_table_file` 函数接收一个 DataFrame 对象和一个文件路径作为参数,将 DataFrame 的数据写入到对应的文件。 在测试代码,我们首先调用 `read_table_file` 函数来读取一个名为 `example.csv` 的表格文件,并将读取到的数据输出到控制台。然后我们创建一个新的 DataFrame 对象,并调用 `write_table_file` 函数将这个 DataFrame 的数据写入到一个名为 `new_example.csv` 的表格文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值