请查看下面的代码以尝试解决标题。无效的部分以“ for row_num”开头,我要用单个值填充列A。我没有收到错误消息,但是当我打开文件时,看到带有“ Form ID”的单元格A1,但是A2列中最大行的A2行为空白(当我希望所有这些都包含“ Test ID”时)谢谢。
wb = load_workbook(filename = 'H:/Hello.xlsx')
ws = wb.worksheets[0]
sheet_names = wb.get_sheet_names()
name = wb.sheetnames[0]
sheet_ranges = wb[name]
df = pd.DataFrame(sheet_ranges.values)
sheet = wb.worksheets[0]
max_row = sheet.max_row
sheet.insert_cols(0)
ws['A1'] = "Form ID"
for row_num in range(2, max_row):
cell = xl_rowcol_to_cell(row_num, 1)
worksheet.write(row_num, 1, 'TESTID')
wb.save("Hello.xlsx")
之前:
xl Date Value
0 1 2
1 2 4
2 3 6
3 4 8
4 5 10
5 6 12
所需的输出:
xl Form_ID Date Value
0 ABC 1 2
1 ABC 2 4
2 ABC 3 6
3 ABC 4 8
4 ABC 5 10
5 ABC 6 12
答案 0 :(得分:1)
如果您想使用熊猫,请使用其矢量化功能。无需手动迭代行:
path = r'H:/Hello.xlsx'
# read file into dataframe
df = pd.read_excel(path)
# add series
df['Form_ID'] = 'TESTID'
# order columns
df = df[['xl', 'Form_ID', 'Date', 'Value']]
# export dataframe
df.to_excel(path, index=False)