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

如何用pandas解析伪装为.xls格式的XML文件并提取第8、11列数据

原因说明

你拿到的是微软XML Spreadsheet 2003格式文件,属于早期的XML类电子表格格式,既不是标准二进制.xls文件,也不是普通结构的XML/HTML/CSV文件,因此pandas自带的读取接口无法直接解析。

解决方案1:纯Python解析(无需额外安装办公软件)

用Python标准XML解析库直接解析文件结构,适配该格式的索引规则即可提取对应列,完整代码如下:

import requests
import xml.etree.ElementTree as ET
import pandas as pd

# 读取文件内容
file_url = "https://pastebin.com/raw/3MQS7RMJ"
resp = requests.get(file_url)
resp.encoding = "utf-8"

# 注册XML命名空间
ns = {"ss": "urn:schemas-microsoft-com:office:spreadsheet"}
root = ET.fromstring(resp.text)

# 遍历所有行提取目标列
extracted_data = []
# 第8列对应索引为7,第11列对应索引为10(列索引从0开始计数)
TARGET_COLS = {7: "col_8", 10: "col_11"}

for row in root.findall(".//ss:Row", ns):
    row_data = {v: None for v in TARGET_COLS.values()}
    current_col_idx = 0
    for cell in row.findall("./ss:Cell", ns):
        # 处理跳过空列的Index属性
        if "{urn:schemas-microsoft-com:office:spreadsheet}Index" in cell.attrib:
            current_col_idx = int(cell.attrib["{urn:schemas-microsoft-com:office:spreadsheet}Index"]) - 1
        # 读取单元格内容
        data_node = cell.find("./ss:Data", ns)
        cell_value = data_node.text if data_node is not None else None
        # 匹配目标列
        if current_col_idx in TARGET_COLS:
            row_data[TARGET_COLS[current_col_idx]] = cell_value
        current_col_idx += 1
    extracted_data.append(row_data)

# 转成DataFrame可直接后续处理
df = pd.DataFrame(extracted_data)
print(df)

解决方案2:格式转换后读取(适合批量处理)

如果本地安装有LibreOffice/OpenOffice,可以直接用命令行工具ssconvert把文件转成标准xlsx格式,再用pandas读取:

  1. 执行转换命令:
    ssconvert 你的本地文件路径.xls 转换后文件路径.xlsx
  2. 直接读取提取列:
import pandas as pd
df = pd.read_excel("转换后文件路径.xlsx")
# 提取第8、11列,索引从0开始
target_df = df.iloc[:, [7, 10]]

内容的提问来源于stack exchange,提问作者Fghjkgcfxx56u

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:24:05