xlsxwriter-从数据库中循环值并存储在电子表格中

时间:2018-11-24 11:40:59

标签: python-3.x xlsxwriter

我有一个存储列定义的表,如下所示:

Col Name : store_name
Definition : name

Col Name : store_location
Definition : location

表结构:

store_name,store_location
name,location

我正在尝试使用以下循环在excel电子表格中显示这些值:

cursor = This queries the table that stores the above info
title_def = [i[0] for i in cursor.description]

row = 5
col = 2

for data in title_def:
    worksheet1.write(row, col, data, header_format)
    row += 1

以上循环仅打印出标签。我不确定如何修改上面的title_def,因为我相信我只是过滤出标题,并且使用xlsxwriter将其显示在工作表中。任何人都可以建议我如何在同一电子表格中同时显示col_name和定义。

1 个答案:

答案 0 :(得分:0)

# Loop through cells in Excel and print values
from openpyxl import load_workbook
workbook = load_workbook('C:\\your_path\\ExcelFile.xlsx')
sheet = workbook.active
row_count = sheet.max_row
for i in range(row_count):
   print(sheet.cell(row=i, column=1).value)


# And if you want to do the same with a CSV file
import csv
with open('C:\\your_path\\CSVFile.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)