我正在尝试使用pandas.df.to_excel()方法创建一个Excel报告。这是我的片段。
r2 = [183, 143]
for item in r2:
cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
row3 = cursor.fetchall()
thi_tuple = [c_tup[0] for c_tup in row3]
r3 += list(map(int, thi_tuple))
print(r3)
df2 = DataFrame({'CMS_ID': item, 'version': r3})
writer2 = ExcelWriter(join(sep, "C:" + sep, "MyCave" + sep, "iso" + sep, "SDG" + sep, "Int" + sep, "latest" + sep, "other_dependencies.xlsx"), engine = 'xlsxwriter')
df2.to_excel(writer2, sheet_name = 'other dependencies', startrow=1, header=False )
workbook = writer2.book
worksheet = writer2.sheets['other dependencies']
for col_num, value in enumerate(df2.columns.values):
worksheet.write(0, col_num + 1, value)
writer2.save()
它正在写入Excel工作表。
不是将r2的两个项目都打印为excel,而是仅打印143。
如何解决逻辑?
致谢
答案 0 :(得分:0)
我将您的代码更改为此:
r2 = [183, 143]
writer2 = ExcelWriter(os.path.join(sep, "tmp" + sep, "other_dependencies.xlsx"), engine = 'xlsxwriter')
for i in range(0, len(r2)):
item = r2[i] # the item here is equal to the item in "for item in r2:"
cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
row3 = cursor.fetchall()
thi_tuple = [c_tup[0] for c_tup in row3]
r3 += list(map(int, thi_tuple))
print(r3)
df2 = DataFrame({'CMS_ID': item, 'version': r3})
df2.to_excel(writer2, sheet_name = 'other dependencies', startrow=i+1, header=False )
workbook = writer2.book
worksheet = writer2.sheets['other dependencies']
for col_num, value in enumerate(df2.columns.values):
worksheet.write(0, col_num + 1, value)
writer2.save()
我将excel文件的创建移到了for循环的外部。而且我还将startrow
更改为变量i
。
i
确定要写入的行。
startrow
从1
开始,而索引r2
从0
开始。这就是为什么我为i+1
写startrow
的原因。