openpyxl: ValueError: dtype: int64 to Excel

openpyxl: ValueError: dtype: int64 to Excel

我正在合并两个 .csv 文件并编写一个新的 .xlsx 文件。

代码如下:

ODEMPTY = pandas.read_csv('OD_Empty_unduplicated.csv')
ODNEW = pandas.read_csv('OD_Out.csv')

ODNEW = ODNEW.append(ODEMPTY)

wb = openpyxl.load_workbook('cm2011.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'][i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'][i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'][i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'][i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'][i]

错误:ValueError:dtype:int64 到 Excel

您目前正在尝试向单元格写入多个 pd.Series。要只获得一个值,您必须使用 .iloc,例如:

for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'].iloc[i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'].iloc[i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'].iloc[i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'].iloc[i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'].iloc[i]

但您可以直接遍历 table:

for i,j in ODNEW.iterrows():
   sheet['A'+ str(i+1)].value = j['ONode']
   sheet['C'+ str(i+1)].value = j['DNode']
   sheet['D'+ str(i+1)].value = j['quantity']
   sheet['E'+ str(i+1)].value = j['startRR']

不然看这里提供的效用函数:http://openpyxl.readthedocs.io/en/default/pandas.html