【发布时间】:2018-06-01 21:33:11
【问题描述】:
我正在尝试使用 python 在 excel 文件中导入 ms sql 数据库数据。我没有在 Excel 表中按正确顺序排列数据。例如,它显示第 1 列数据,然后显示第 3 列,然后显示第 2 列,然后显示第 4 列,依此类推。 我正在使用以下脚本:
import pyodbc
import csv
connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=MS-DC-06,49208;"
"Database=****;"
"uid=**;pwd=***")
cursor = connection.cursor()
cursor.execute("select top 10 * from Api_NotificationEntry")
data=cursor.fetchall()
for col in data:
with open('dataTester.csv', 'a', newline='') as fp:
a= csv.writer(fp, delimiter=',')
a.writerow({col[0],col[1]})
cursor.close()
connection.close()
它应该显示如下数据:
10 2689
11 2689
12 2689
13 2689
14 2689
15 2689
16 2689
8 2673
17 2689
19 3083
但它在 excel 表中显示如下:
Col1 Col2
65509
10
2689
65509
10
2689
65509
2689 10
2689 65509
6218 65509
2689 10
2689 65509
6218 65509
2689 10
2689 11
2689 12
2689 13
2689 14
2689 15
16 2689
8 2673
17 2689
3083 19
【问题讨论】:
-
当你用 TextEditor 打开数据时,它是什么样子的?可以提供截图吗?
-
您正在打开文件并为每一行数据创建 csv 写入器
-
@Vityata 我在问题中添加了截图。
-
@FujiApple 是的,我想在 excel 中使用它,还有什么其他选择?
-
@KhurramRaftaz - 在记事本中打开它,而不是使用 Excel。
标签: python sql-server excel import