从csv输入文件逐行填充excel文件

2024-09-27 04:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个csv文件,有多行:

column1,column2,column3,column4,colunm5,column6
valueA,valueB,valueC,valueD,valueE,valueD
valueA,valueB,valueC,valueD,valueE,valueD
...

另一方面,我有一个excel文件,我想在其中填充某些特定单元格上的一些csv逐行值,例如:

column1 and valueA into the excel file in the cell D7.
column2 and valueB into the excel file in the cell E8.
column3 and valueC into the excel file in the cell F8.
column4 and valueC into the excel file in the cell G8.
column5 and valueC into the excel file in the cell H8.
column6 and valueC into the excel file in the cell I8.

完成每行的列/值后,保存一个文件,然后继续csv文件的下一行并保存一个新文件

我试过这样的方法:

from openpyxl import load_workbook
import csv

wb = load_workbook('templatefile.xlsx')
ws = wb.get_active_sheet()
with open('source.csv') as fin:
    reader = csv.reader(fin, delimiter=',')
        row = row[0].split()
        ws.cell(row=index, column=1).value = row[2]
        ws.cell(row=index, column=2).value = row[3]
# save the file
wb.save("out1.xlsx")

没有成功。你怎么能做到这一点?有什么建议吗

谢谢


Tags: and文件csvtheincellexcelfile
1条回答
网友
1楼 · 发布于 2024-09-27 04:19:55

我不懂python,但我相信逻辑应该是这样的:

wb = load_workbook('templatefile.xlsx')
ws = wb.get_active_sheet()
i = 1
with open('source.csv') as fin:
    reader = csv.reader(fin, delimiter=',')
        row = row[0].split()
        ws.cell(row[i], column=1).value = row[2]
        ws.cell(row=[i], column=2).value = row[3]
        i = i+1
# save the file
wb.save("out1.xlsx")

相关问题 更多 >

    热门问题