pandas.ExcelWriter ValueError:xlsxwriter不支持追加模式

时间:2019-02-25 09:40:03

标签: python-3.x pandas pandas.excelwriter

我想向Excel文件中添加一些记录,然后使用pandas.ExcelWriter进行此操作(http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html?highlight=excelwriter#pandas.ExcelWriter ):

import pandas as pd                                                     

df = pd.DataFrame(data={'a':[4], 'b':['corn'], 'c':[0.5]})              

with pd.ExcelWriter("test.xlsx", mode='a') as writer: 
            df.to_excel(writer) 

a,b,c是test.xlsx的标题名称

运行此程序,引发valueError:

ValueError                                Traceback (most recent call last)
<ipython-input-3-c643d22b4217> in <module>
----> 1 with pd.ExcelWriter("test.xlsx", mode='a') as writer:
      2     df.to_excel(writer)
      3 

~/anaconda/lib/python3.6/site-packages/pandas/io/excel.py in __init__(self, path, engine, date_format, datetime_format, mode, **engine_kwargs)
   1935 
   1936         if mode == 'a':
-> 1937             raise ValueError('Append mode is not supported with xlsxwriter!')
   1938 
   1939         super(_XlsxWriter, self).__init__(path, engine=engine,

ValueError: Append mode is not supported with xlsxwriter!

我不知道为什么?

5 个答案:

答案 0 :(得分:4)

解决了这个问题,在模式下使用大写字母A,就可以了!

    import pandas as pd                                                     

    df = pd.DataFrame(data={'a':[4], 'b':['corn'], 'c':[0.5]})              

    with pd.ExcelWriter("test.xlsx", mode='A') as writer: 
        df.to_excel(writer)

答案 1 :(得分:2)

如回溯所示,controllerSample.getControllerSending().getControllerSendingPhotos()

我不能回答你的问题,为什么,这是熊猫开发者的决定。

但是我能够使您的用例与Pandas 0.24和ValueError: Append mode is not supported with xlsxwriter!一起使用:

openpyxl

答案 2 :(得分:1)

尝试将“引擎”指定为openpyxl:

with pd.ExcelWriter("test.xlsx", engine='openpyxl', mode='a') as writer:
    df.to_excel(writer)

答案 3 :(得分:1)

尝试一下:

with pd.ExcelWriter("existing_file_name.xlsx", engine="openpyxl", mode="a") as writer:
    df.to_excel(writer, sheet_name="name", startrow=num, startcol=num)

您需要将引擎指定为“ openpyxl”。

答案 4 :(得分:0)

哼,我很确定您不能在xlsxwriter中使用附加到现有xlsx文件的功能,因为xlsxwriter库仅用于写入excel文件

See the issue on Github

因此您可以使用openpyxl或更好地编写程序来执行此功能。

但是,如果您查看此libray中的代码,它只是在临时环境中读取文件,然后才写入最终文件,这不是真正的附加...