[英]How do I save data from MySQL db to excel file as Number not text using Python
Below is the script. 下面是脚本。 I am pulling some data and save to Excel In the output file, all column are marked "Number stored as Text" What can I do in the script to change all columns to number (int)? 我要提取一些数据并保存到Excel中在输出文件中,所有列都标记为“数字存储为文本”。在脚本中我该怎么做才能将所有列更改为数字(int)? Thanks 谢谢
wb = openpyxl.Workbook()
db = MySQLdb.connect(host="...",port=...,user="...",passwd="...",db='...')
cursor = db.cursor()
cursor.execute("""
SELECT shopid,userid,count(orderid)as no_of_orders
from order_viw
group by shopid,userid
""")
data = cursor.fetchall()
rowNum = 2
col = 1
sheet = wb.get_sheet_by_name("Sheet")
for shopid,userid,no_of_orders in data:
sheet.cell(column=col, row=rowNum, value="%d" % shopid)
sheet.cell(column=col+1, row=rowNum, value="%d" % userid)
sheet.cell(column=col+2, row=rowNum, value="%d" % no_of_orders)
rowNum += 1
wb.save('C:/example.xlsx')
db.close()
As a forewarning, I'm running on Linux, have not got a MySql database and I am using libreoffice to check the results. 作为警告,我正在Linux上运行,还没有MySql数据库,并且我使用libreoffice检查结果。
With those caveats in place, the following looks like it works for me: 有了这些警告之后,以下内容似乎对我有用:
import openpyxl
wb = openpyxl.Workbook()
rowNum = 2
col = 1
sheet = wb.get_sheet_by_name("Sheet")
#data = [[42,1,43],[82,2,28]]
data = [['42','1','43'],['82','2','28']]
for shopid,userid,no_of_orders in data:
sheet.cell(column=col, row=rowNum).value=int(shopid)
sheet.cell(column=col+1, row=rowNum).value=int(userid)
sheet.cell(column=col+2, row=rowNum).value=int(no_of_orders)
rowNum += 1
wb.save('example.xlsx')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.