问题
I have a csv file like this with multiple lines:
column1,column2,column3,column4,colunm5,column6
valueA,valueB,valueC,valueD,valueE,valueD
valueA,valueB,valueC,valueD,valueE,valueD
...
In the other hand I have an excel file where I want to fill it with some of the csv line by line values on certain specific cells, for example:
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.
When finish columns/values per line, save a file and continue with the next line of the csv file and a new file saved.
I tried with something like:
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")
Without success. How can do this? Any suggestion?
Thanks,
回答1:
I don't know python but I believe the logic should be something like that:
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")
来源:https://stackoverflow.com/questions/61966833/populate-an-excel-file-from-csv-input-file-line-by-line