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

使用xlwings写入Excel时浮点数被转为货币格式的解决方法

问题:xlwings写入Excel时浮点数被自动转为货币格式的解决办法

我通过xlwings连接Snowflake提取了包含文本、日期和浮点数类型的Pandas DataFrame,用df.to_excel验证过格式完全正常,但用xlwings写入Excel工作簿时,浮点数被自动转换成了货币格式。尝试过添加.options(index=False, numbers=float)参数,但是没有效果,求能保持DataFrame原格式的解决方案。

相关代码如下:

# Fetch the results
results = cur.fetchall()

# Fetch the column names
column_names = [desc[0] for desc in cur.description]

# Close the cursor and connection
cur.close()
conn.close()

df = pd.DataFrame(results, columns=column_names)

# Open an Excel workbook
wb = xw.Book.caller()

# Select the sheet you want to write to
sheet = wb.sheets['Snowflake'] 
sheet.range('A1').options(index=False).value = df

解决方案

方法1:写入后批量设置单元格格式

先完成数据写入,再针对浮点数列手动设置Excel格式:

# 写入DataFrame数据
sheet.range('A1').options(index=False).value = df

# 遍历列,识别浮点数类型并设置格式
for col_idx, dtype in enumerate(df.dtypes):
    if str(dtype).startswith('float'):
        # Excel列索引从1开始,对应df的列索引+1
        target_col = col_idx + 1
        # 设置为常规格式,也可替换为'0.00'这类自定义数值格式
        sheet.range(1, target_col).expand('down').number_format = 'General'

方法2:借助df.to_excel的正确格式间接写入

既然df.to_excel能保持正确格式,可先写入临时文件,再复制到目标工作簿:

import tempfile
import os

# 生成临时Excel文件
with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as temp_file:
    df.to_excel(temp_file, index=False)

# 打开临时文件并复制数据
temp_wb = xw.Book(temp_file.name)
temp_sheet = temp_wb.sheets[0]
temp_sheet.used_range.copy(destination=sheet.range('A1'))

# 清理临时文件
temp_wb.close()
os.unlink(temp_file.name)

方法3:直接在options中指定Excel格式字符串

xlwings的options参数里,numbers可以接收Excel格式字符串,直接指定浮点数的显示格式:

# 设置为常规格式
sheet.range('A1').options(index=False, numbers='General').value = df

# 或者设置为保留两位小数的数值格式
# sheet.range('A1').options(index=False, numbers='0.00').value = df

内容的提问来源于stack exchange,提问作者Toby-wan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:10