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

如何让pandas read_excel保留Excel可视化显示的原始数据格式

解决方案:保留Excel原始显示格式读取/自动化转CSV

一、推荐直接读取原始显示文本的库

1. xlrd(仅支持.xls格式)

通过参数配置强制读取单元格的显示文本:

import xlrd

workbook = xlrd.open_workbook('your_file.xls', formatting_info=True)
sheet = workbook.sheet_by_index(0)

# 遍历单元格提取显示文本
for row in range(sheet.nrows):
    row_data = []
    for col in range(sheet.ncols):
        cell = sheet.cell(row, col)
        # 针对日期类型做格式转换,其他类型直接取值转字符串
        text = xlrd.xldate_as_text(cell.value, workbook.datemode) if cell.ctype == xlrd.XL_CELL_DATE else cell.value
        row_data.append(str(text))
    print(row_data)

2. openpyxl(支持.xlsx格式)

通过单元格的number_format属性匹配Excel原始格式,转换为对应显示文本:

from openpyxl import load_workbook
from datetime import datetime

wb = load_workbook('your_file.xlsx', data_only=True)
ws = wb.active

for row in ws.iter_rows(values_only=False):
    row_data = []
    for cell in row:
        if cell.data_type == 'd':
            # 映射Excel日期格式为Python strftime格式,生成显示文本
            fmt = cell.number_format
            py_fmt = fmt.replace('yyyy', '%Y').replace('mm', '%m').replace('dd', '%d')
            row_data.append(datetime.strftime(cell.value, py_fmt))
        elif cell.data_type == 'n':
            # 根据数字格式保留小数位数或转为整数显示
            fmt = cell.number_format
            if '0.00' in fmt:
                row_data.append(f"{cell.value:.2f}")
            else:
                row_data.append(str(int(cell.value)) if cell.value.is_integer() else str(cell.value))
        else:
            row_data.append(str(cell.value))
    print(row_data)

3. win32com.client(Windows环境,调用Excel原生接口)

完全模拟手动操作,精准获取Excel界面显示的原始文本:

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
wb = excel.Workbooks.Open(r'your_file.xlsx')
ws = wb.Worksheets(1)

# 提取所有已用单元格的显示文本
data = []
for row in ws.UsedRange.Rows:
    row_data = []
    for cell in row.Cells:
        row_data.append(cell.Text)
    data.append(row_data)

wb.Close(False)
excel.Quit()

二、自动化将Excel转为CSV(保留显示格式)

利用win32com.client模拟手动另存为CSV的操作,导出效果和手动操作完全一致:

import win32com.client as win32

def excel_to_csv(excel_path, csv_path):
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    wb = excel.Workbooks.Open(excel_path)
    # 6对应CSV格式,直接按Excel显示格式导出
    wb.SaveAs(csv_path, FileFormat=6)
    wb.Close(False)
    excel.Quit()

# 调用示例
excel_to_csv('test.xlsx', 'output.csv')

注意:该方法仅适用于Windows环境,需提前安装Office Excel。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:26:03