Python 操作 xls 表:高效提取与转移

177次阅读
没有评论

共计 1943 个字符,预计需要花费 5 分钟才能阅读完成。

Python 作为一种强大的编程语言,在操作 xls 表方面具有显著的优势和广泛的应用场景。

首先,Python 提供了多个专门用于操作 Excel 文件的库,为不同需求的用户提供了丰富的选择。例如,openpyxl 专为.xlsx 格式设计,功能丰富,支持读写单元格、样式设置、图表生成等,性能相对较好,适合处理大型工作簿。pandas 则具有强大的数据处理和分析能力,与 NumPy 紧密集成,可支持多种数据格式,包括 Excel,尤其适用于数据清洗、转换和分析。对于.xls 格式的文件,xlrd 和 xlwt 的组合可以实现基本的读写功能,虽然功能相对简单,但易于上手。本文使用 xlrd 和 xlwt 操作 xls 表格,代码如下:

import xlrd
import xlwt
import pandas as pd
import re
from datetime import datetime
from tkinter import Tk, filedialog


def open_excel_file():
    """打开文件选择对话框,选择 .xls Excel 文件"""
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    file_path = filedialog.askopenfilename(
        title="选择 Excel 文件",
        filetypes=[("Excel 文件", "*.xls")]
    )
    return file_path


def copy_rows_based_on_date(input_file):
    # 打开 .xls 文件
    workbook = xlrd.open_workbook(input_file, formatting_info=True)

    # 尝试打开名为“在职 1 页”的工作表
    try:
        source_sheet = workbook.sheet_by_name("在职 1 页")
    except xlrd.biffh.XLRDError:
        print("未找到' 在职 1 页 '工作表")
        return

    # 创建新的工作簿和工作表
    new_workbook = xlwt.Workbook()
    new_sheet = new_workbook.add_sheet("98 后")

    # 复制表头(假设表头占前 4 行)for row in range(4):
        for col in range(source_sheet.ncols):
            new_sheet.write(row, col, source_sheet.cell_value(row, col))

    # 设置日期筛选条件
    cutoff_date = datetime(1998, 1, 1)

    # 初始化“98 后”表的行索引,从第 5 行开始写入数据
    new_row_index = 4

    # 从第 5 行开始遍历数据行
    for row in range(4, source_sheet.nrows):
        # 获取第 31 列(即 AE 列)的值
        cell_value = source_sheet.cell_value(row, 30)  # 第 31 列的索引是 30

        # 尝试将单元格值转换为日期
        try:
            # 将 Excel 序列号转为日期格式
            # date_value = datetime(*xlrd.xldate_as_tuple(cell_value, workbook.datemode))
            date_value = datetime.strptime(cell_value, '%Y-%m-%d')

            # 检查日期是否大于 1998-01-01
            if date_value > cutoff_date:
                # 复制符合条件的整行数据
                for col in range(source_sheet.ncols):
                    new_sheet.write(new_row_index, col, source_sheet.cell_value(row, col))
                new_row_index += 1
        except (ValueError, TypeError):
            continue

    # 保存新的 Excel 文件
    match = re.search(r'(\d{4})(\d{2})', input_file)
    if match:
        year, month = match.groups()
        file2 = f'{year}-{month}'
    else:
        file2 = None

    output_file = input_file.replace(".xls", "-98 后.xls")
    new_workbook.save(output_file)
    print(f"已完成处理,保存为新文件:{output_file}")


# 主程序入口
if __name__ == "__main__":
    excel_file = open_excel_file()
    if excel_file:
        copy_rows_based_on_date(excel_file)
    else:
        print("未选择文件,程序结束。")
正文完
 0
评论(没有评论)