You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需使用Pandas:Python提取Excel中1396-1577行数据的代码需求

提取Excel指定行与列数据(不使用Pandas)

如果你的Excel文件是.xlsx格式,推荐使用openpyxl库(原生支持xlsx,适配大文件处理);如果是旧版.xls格式,用xlrd库(注意:xlrd 2.0+不再支持xlsx,需安装1.2.0版本)。以下是两种场景的实现代码:

场景1:处理.xlsx文件(使用openpyxl)

from openpyxl import load_workbook
from openpyxl import Workbook

# 配置参数
source_file = "你的源文件路径.xlsx"
target_file = "提取结果.xlsx"
sheet_name = "Sheet1"  # 替换为你的工作表名称
start_row = 1396
end_row = 1577
target_columns = ["A", "C", "E"]  # 替换为你需要提取的列名,比如["B", "D"]

# 加载源工作簿(只读模式适配大文件)
wb_source = load_workbook(source_file, read_only=True)
ws_source = wb_source[sheet_name]

# 创建目标工作簿
wb_target = Workbook()
ws_target = wb_target.active

# 写入表头(不需要可删除此段)
header = [ws_source[col + "1"].value for col in target_columns]
ws_target.append(header)

# 提取指定行和列数据
for row_num in range(start_row, end_row + 1):
    row_data = []
    for col in target_columns:
        cell_value = ws_source[col + str(row_num)].value
        row_data.append(cell_value)
    ws_target.append(row_data)

# 保存并关闭文件
wb_target.save(target_file)
wb_source.close()

关键点说明:

  • read_only=True:针对大文件启用只读模式,大幅降低内存占用,提升处理速度。
  • 行号直接使用Excel原生的1起始编号,range(start_row, end_row + 1)确保包含1577行。
  • target_columns可灵活修改,比如需要提取第2、4列,可写为["B", "D"]。

场景2:处理.xls文件(使用xlrd)

import xlrd
import xlwt

# 配置参数
source_file = "你的源文件路径.xls"
target_file = "提取结果.xls"
sheet_index = 0  # 工作表索引从0开始
start_row = 1395  # xlrd行索引从0开始,1396行对应索引1395
end_row = 1576    # 1577行对应索引1576
target_cols = [0, 2, 4]  # 列索引从0开始,A列是0,C列是2

# 加载源文件
wb_source = xlrd.open_workbook(source_file)
ws_source = wb_source.sheet_by_index(sheet_index)

# 创建目标工作簿
wb_target = xlwt.Workbook()
ws_target = wb_target.add_sheet("提取结果")

# 写入表头(不需要可删除此段)
header = ws_source.row_values(0)  # 假设表头在第1行(索引0)
for col_idx, col in enumerate(target_cols):
    ws_target.write(0, col_idx, header[col])

# 提取数据
row_idx = 1  # 目标表从第2行开始写数据
for source_row in range(start_row, end_row + 1):
    row_data = ws_source.row_values(source_row)
    for col_idx, col in enumerate(target_cols):
        ws_target.write(row_idx, col_idx, row_data[col])
    row_idx += 1

# 保存结果
wb_target.save(target_file)

关键点说明:

  • xlrd的行、列索引均从0开始,需将Excel原生行号减1转换为索引。
  • 若无需保留表头,直接删除写入表头的代码块即可。

内容的提问来源于stack exchange,提问作者sai sasank 21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:01:43