【问题标题】:Import ms sql database data in excel file using python使用python在excel文件中导入ms sql数据库数据
【发布时间】: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

This is how it looks like in excel screenshot

This is how it looks like in notepad

【问题讨论】:

  • 当你用 TextEditor 打开数据时,它是什么样子的?可以提供截图吗?
  • 您正在打开文件并为每一行数据创建 csv 写入器
  • @Vityata 我在问题中添加了截图。
  • @FujiApple 是的,我想在 excel 中使用它,还有什么其他选择?
  • @KhurramRaftaz - 在记事本中打开它,而不是使用 Excel。

标签: python sql-server excel import


【解决方案1】:

从数据库中获取数据后,我使用 python 脚本过滤它们,

a.writerow({col[0],col[1]})

这不是在csv文件中以正确的顺序写入数据,因此解决方案是使用sql查询从数据库中获取过滤数据,而不是在python脚本中对其进行过滤。这已经解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多