Home > front end >  How to insert values form sqlite to excel without brackets and in specific column (Python)?
How to insert values form sqlite to excel without brackets and in specific column (Python)?

Time:03-10

I am new to Python. I want to know how to add values into an excel file. I did some research on google but I still can't find the way to make it. This is what I have:

wb = load_workbook('example.xlsx')
ws = wb.active
con = sqlite3.connect(database=r'database.db')
cur = con.cursor()
cur.execute("Select colors from store")
row= cur.fetchall()
ws['B14'].value = str(row)

With these code, it shows all the values in column B14 with brackets. What I want is

  1. Each value in a column within B14 to B33
  2. The value without brackets

Anyone help with this?

CodePudding user response:

.fetchall returns a list of tuples, and str(row) gives you the string representation of that list.

If you want each individual element of this list in its own cell you'll need to iterate over the list and modify the cell name in each iteration:

row_num = 14
for elem in cur.fetchall():
    ws[f'B{row_num}'].value = elem[0]
    row_num  = 1

Another way, with enumerate:

starting_row_num = 14
for row_num, elem in enumerate(cur.fetchall(), starting_row_num):
    ws[f'B{row_num}'].value = elem[0]
  • Related