python 实现excel创建及

1.引入包

import xlrd as xlrd
import xlwt
from xlutils.copy import copy

2.excel创建

styleBoldRed = xlwt.easyxf('font: color-index black, bold on')
headerStyle = styleBoldRed
wb = xlwt.Workbook()
ws = wb.add_sheet('all_comments')
ws.write(0, 0, "id", headerStyle) #“0”,“0”表示第0行第0列"id"为cexel表中的列标题名称
ws.write(0, 1, "comment", headerStyle)
ws.write(0, 2, "timestamp", headerStyle)
wb.save('C:\Users\Administrator\Desktop\course_list\\'+category+'\\'+course+'.xlsx')#excel存入的路径

3.excel写入

oldWb = xlrd.open_workbook("C:\Users\Administrator\Desktop\course_list" + "\\" +category+'\\'+ random_course+".xlsx")
oldWbS = oldWb.sheet_by_index(0)
newWb = copy(oldWb)  # a writable copy (I can't read values out of this, only write to it)
newWs = newWb.get_sheet(0)  # the sheet to write to within the writable copy

inserRowNo = 1
newWs.write(inserRowNo, 0, ’comment‘)#comment为插入的数据
newWs.write(inserRowNo, 1, ‘rating’)
newWs.write(inserRowNo, 2, ’timestamp‘)
for rowIndex in range(inserRowNo, oldWbS.nrows):
    for colIndex in range(oldWbS.ncols):
        newWs.write(rowIndex + 1, colIndex, oldWbS.cell(rowIndex, colIndex).value)
newWb.save('C:\\Users\\Administrator\Desktop\course_list\\'+category+'\\'+random_course+'.xlsx')
print "save information ok"

要注意的是:创建excel和写入excel要写在两个函数中,在创建excel的函数后面调用写入excel的函数即可实现创建和写入一次性完成。


参考网址:

python xlwt,xlutils 在excel里面如何插入一行数据







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值