python 实现excel创建及

来源:互联网 发布:罗马人的故事版本知乎 编辑:程序博客网 时间:2024/06/05 06:37

1.引入包

import xlrd as xlrdimport xlwtfrom xlutils.copy import copy

2.excel创建

styleBoldRed = xlwt.easyxf('font: color-index black, bold on')headerStyle = styleBoldRedwb = 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 copyinserRowNo = 1newWs.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里面如何插入一行数据