python导出excel,csv

pyhton导出excel

conn = pymysql.connect(
    host = '10.0.122.120',
    port = 3306,
    user = 'rourou',
    passwd = 'QFedu123!'
)

cursor = conn.cursor()

cursor.execute("use dj21gp01")
cursor.execute("select * from idc")
col = cursor.description

data = cursor.fetchall()

wb = xlwt.Workbook()

ws = wb.add_sheet("dj21gp01",cell_overwrite_ok=True)

for i in range(len(col)):
    ws.write(0,i,col[i][0])

row = 1
for item in data:
    for j in range(len(item)):
        ws.write(row,j,item[j])
    row += 1

wb.save("/root/桌面/test.xls")

cursor.close()

python 导出csv

import csv
with open('/root/桌面/csv.csv', "w", encoding='utf8', newline='') as outFileCsv:
    #设置csv表头
    fileheader = ['姓名', '年龄']
    outDictWriter = csv.DictWriter(outFileCsv, fileheader)
    outDictWriter.writeheader()
    #设置csv数据,这里的数据格式是字典型
    result = [{'姓名': '张三', '年龄': 12}, {'姓名': '李四', '年龄': 14}]
    outDictWriter.writerows(result)
    outFileCsv.close()


import csv
with open('/root/桌面/ceshi.csv', 'w', encoding='utf8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        #设置表头
        result = ['姓名', '年龄']
        writer.writerow(result)
        #将CsvData中的数据循环写入到csv文件中
        CsvData = [['张三','22'],['李四','44']]
        for item in CsvData:
            writer.writerow(item)

你可能感兴趣的:(python导出excel,csv)