python3使用xlwt模块操作excel

和读操作分开写了两份笔记,后面还需要更新一个更新excel的笔记,写入数据也基本就四步操作

第一步:

创建excel文件

第二步:

创建工作簿对象

第三步:

写入表头数据

第四步:

循环写入数据

具体代码如下

#!/usr/bin/python3
#coding:utf-8
import xlwt

#创建excel
book = xlwt.Workbook(encoding='utf-8')
#创建工作簿
sheet = book.add_sheet(u'工作资料')
#创建工作簿内容表头
rows = [u'id', u'姓名', u'昵称']
#二维列表测试数据
cols = [[2, u'苏阳', u'merci'], [3, u'苏走', 'shevechco'], [4, u'测试', 'test'], [4, u'测试2', 'test2']]
#写入表头
for i in range(len(rows)):
    sheet.write(0, i, rows[i])

#循环写入数据
for n in range(len(cols)):
    for k in range(len(cols[n])):
        #从第二行开始写,遍历k列数据
        sheet.write(n+1, k, cols[n][k])

book.save('test.xls')

成功截图,代码注释的很详细,可以自己尝试多操作几遍

menu.saveimg.savepath20181224162513.jpg


下面是导出我网站的数据的实例代码,可以参考下

#!/usr/bin/python3
#coding:utf-8
import pymysql
import xlwt

def write_excel(data):
    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet(u'苏老的数据')
    #表头
    rows = ['id', 'catid', 'title', 'posttime', 'nums']
    #写入表头
    try:
        for i in range(len(rows)):
            sheet.write(0, i , rows[i])
    except:
        print("写入表头失败!")
    #写入数据
    try:
        for p in range(len(data)):
            for k in range(len(data[p])):
                sheet.write(p+1, k, data[p][k])
    except:
        print("写入数据失败!")
        
    book.save('sulao.xls')

def get_con():
    conn = False
    try:
        conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='sulao', charset='utf8')
    except:
        print("Connect failed !")
        conn = False
    return conn

def get_data():
    cursor = get_con().cursor()
    sql = """SELECT log_ID,log_CateID,log_Title,log_PostTime,log_ViewNums FROM zbp_post WHERE log_Status=0 ORDER BY log_ID ASC"""
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

if __name__ == "__main__":
    data = get_data()
    write_excel(data)

导出如下数据

menu.saveimg.savepath20181224170147.jpg


内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/607.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。