python3 implements mysql export excel

Posted by SystemOverload on Thu, 02 Jul 2020 17:02:27 +0200

I. Preparations

Python Tool Library Installation xlwt and xlrd Installation under 1.1win7

1.1.1 Method 1: Download and Install

1. From http://pypi.python.org/pypi/xlwt Download xlwt-1.0.0.tar.gz;
2. From http://pypi.python.org/pypi/xlrd Download xlrd-0.9.4.tar.gz;
3. Unzip the package;
4. Run under win7.
[plain] view plain copy
cmd
Switch to the corresponding decompression path
[plain] view plain copy
F:
cd xlrd-0.9.4
5. Installation
[plain] view plain copy
setup.py install
xlwt is the same.

1.1.2 Method 2: Command Prompt (Recommended)

Python3 can be entered at the command prompt

pip3 install xlrd
pip3 install xlwt

- Python2 direct input

pip install xlrd
pip install xlwt

1.2 windows system python35 install mysql-python

After searching for half a day, I found that python3 does not support mysql-python. What a painful insight!!!
Install third-party package pymysql.
Download address: https://pypi.python.org/pypi/PyMySQL#downloads

Usage method:
import pymysql as MySQLdb

2. Code implementation

# coding:utf8  
import sys  
import xlwt  
#import MySQLdb
import pymysql as MySQLdb
import datetime  

host = 'Host Address'  
user = 'root'  
pwd = 'Password'  
db = 'Database Name'  
sql = 'select * from form'  
sheet_name = 'building'  
out_path = '..\data\data_excel\one.xls'


conn = MySQLdb.connect(host,user,pwd,db,charset='utf8')  
cursor = conn.cursor()  
count = cursor.execute(sql)  
print(count)  

cursor.scroll(0,mode='absolute')  
results = cursor.fetchall()  
fields = cursor.description  
workbook = xlwt.Workbook()  
sheet = workbook.add_sheet(sheet_name,cell_overwrite_ok=True)  

for field in range(0,len(fields)):  
    sheet.write(0,field,fields[field][0])  

row = 1  
col = 0  
for row in range(1,len(results)+1):  
    for col in range(0,len(fields)):  
        sheet.write(row,col,u'%s'%results[row-1][col])  

workbook.save(out_path)

3. Python 3 Implements mysql Export TXT

Code is simple and needs improvement

# coding=utf-8  
'''''  
main function: The main implementation will txt Write each row of data in excel in 
'''  

#################  
#Code executed for the first time  
import xlwt #write file  
import xlrd #Open excel file  

fopen=open("..\data\\data_txt\\a.txt",'r',encoding = 'utf-8')  
lines=fopen.readlines()  
#Create a new excel file  
file=xlwt.Workbook(encoding='utf-8',style_compression=0)  
#Create a new sheet  
sheet=file.add_sheet('data')  

############################  
#Write to a.txt, a.txt file has 20,000 lines  
i=0  
for line in lines:  
    sheet.write(i,0,line)  
    i=i+1  

#################################  
#The second level executes the code, writing b.txt,
"""
j=20001 #Write from line 2001  
fopen2=open("e:\\a\\bb\\b.txt",'r')  
lines2=fopen2.readlines()  
for line in lines2:  
    sheet.write(j,0,line)  
    j=j+1
"""
file.save('minni.xls')  

Topics: Python MySQL Excel pip