使用xlwt,将SQL选择查询结果插入到xls中的单元格

时间:2018-08-15 14:16:44

标签: python

我正在尝试将sql select查询的结果写入xls文件。 下面是代码:

RowNum = 8
sql = """select * from #table"""
cursor = self.db_conn.cursor()
cursor.execute(sql)
rb = open_workbook(settings.FILE_NAME,formatting_info=True)
wb = copy(rb)

sheet1 = wb.get_sheet('Sheet 1')

for row in cursor.fetchall():
    sheet1.write(RowNum, 0, row) # row, column, value
    RowNum = RowNum + 1

wb.save(settings.FILE_NAME_New)

但是出现以下错误:

sheet1.write(RowNum, 0, row) # row, column, value
  File "python-3.4.3\lib\xlwt\Worksheet.py", line 1088, in write
    self.row(r).write(c, label, style)
  File "python-3.4.3\lib\xlwt\Row.py", line 254, in write
    raise Exception("Unexpected data type %r" % type(label))
Exception: Unexpected data type <class 'pyodbc.Row'>

我哪里出错了?

2 个答案:

答案 0 :(得分:1)

row不是文字值,而是pyodbc.Row。根据所需行的哪一列的值,使用以下命令:

column_number = 0
sheet1.write(RowNum, 0, row[column_number]) # row, column, value

答案 1 :(得分:0)

您需要提及column_number,您正在尝试在文件而不是特定列上写入pyodbc对象。

RowNum = 8
sql = """select * from #table"""
cursor = self.db_conn.cursor()
cursor.execute(sql)
rb = open_workbook(settings.FILE_NAME,formatting_info=True)
wb = copy(rb)

sheet1 = wb.get_sheet('Sheet 1')
column_no = 0
for row in cursor.fetchall():
    sheet1.write(RowNum, 0, row[column_no]) # change this line
    RowNum = RowNum + 1

wb.save(settings.FILE_NAME_New)