使用xlwings将Dataframe写入Excel时遇OverflowError报错求助
解决xlwings写入Dataframe到Excel时的OverflowError问题
问题说明
使用xlwings将Dataframe写入Excel模板时,触发OverflowError: int too big to convert错误,报错发生在Dataframe写入单元格的步骤。
代码片段
app = xw.App() app.display_alerts = False # 打开模板 wb = xw.Book(template) sht = wb.sheets["Flash"] sht.range('A2').options(index=False,header=False).value = df # 写入Dataframe wb.api.RefreshAll() wb.save(xl) wb.close() app.quit() xw.apps
完整报错回溯
Traceback (most recent call last): File "C:\Users\RAVINDRA.K\OneDrive - KPK FASERV INDIA PVT LTD\My Projects\IMEi\IMEI FLASH WH WISE.py", line 441, in <module> sht.range('A2').options(index=False,header=False).value = df #copy the dataframes File "C:\Program Files\Python39\lib\site-packages\xlwings\main.py", line 1803, in value conversion.write(data, self, self._options) File "C:\Program Files\Python39\lib\site-packages\xlwings\conversion\__init__.py", line 48, in write pipeline(ctx) File "C:\Program Files\Python39\lib\site-packages\xlwings\conversion\framework.py", line 66, in __call__ stage(*args, **kwargs) File "C:\Program Files\Python39\lib\site-packages\xlwings\conversion\standard.py", line 74, in __call__ self._write_value(ctx.range, ctx.value, scalar) File "C:\Program Files\Python39\lib\site-packages\xlwings\conversion\standard.py", line 62, in _write_value rng.raw_value = value File "C:\Program Files\Python39\lib\site-packages\xlwings\main.py", line 1399, in raw_value self.impl.raw_value = data File "C:\Program Files\Python39\lib\site-packages\xlwings\_xlwindows.py", line 808, in raw_value self.xl.Value = data File "C:\Program Files\Python39\lib\site-packages\xlwings\_xlwindows.py", line 103, in __setattr__ return setattr(self._inner, key, value) File "C:\Program Files\Python39\lib\site-packages\win32com\client\__init__.py", line 482, in __setattr__ self._oleobj_.Invoke(*(args + (value,) + defArgs)) OverflowError: int too big to convert
问题原因
Excel支持的最大整数为2^53-1(即9007199254740991),当Dataframe中存在超过该范围的整数(比如IMEI这类15位以上的长数字)时,xlwings尝试将超大整数写入Excel时会触发溢出错误。
解决方案
方案1:提前将Dataframe中的超大整数列转为字符串
找到Dataframe中包含超大整数的列(比如IMEI列),转换为字符串类型后再写入:
# 示例:将"IMEI"列转为字符串 df["IMEI"] = df["IMEI"].astype(str) # 执行写入操作 sht.range('A2').options(index=False, header=False).value = df
方案2:通过xlwings的options指定数据类型
直接在写入时通过dtype参数指定列类型为字符串,避免自动转换:
# 所有列都以字符串写入 sht.range('A2').options(index=False, header=False, dtype=str).value = df # 仅指定特定列(比如第1列)为字符串 sht.range('A2').options(index=False, header=False, dtype={0: str}).value = df
额外检查
确认Dataframe中所有列的数值范围,确保没有其他超出Excel整数限制的列,统一处理即可解决该错误。
内容的提问来源于stack exchange,提问作者ravindrakdr
相关产品推荐
相关产品推荐

