python(写入 excel 操作 xlwt 模块)

一、安装 xlwt 模块

  • pip install xlwt

二、excel 写入操作

  • 这种方式只能新增或者覆盖文件写入
import xlwt

# 创建一个workbook 设置编码
workbook = xlwt.Workbook(encoding = 'utf-8')
# 创建一个sheet worksheet = workbook.add_sheet('My Worksheet')
# 写入excel,write(row_index,col_index,value)参数对应 行, 列, 值 worksheet.write(1,0,'this is test')
# 保存(保存后在目录下新增xxx.xls文件) workbook.save('d:\Excel_test.xls')
  • 这种方式进行修改文件内容,不会覆盖原文件内容,只会修改指定的内容 
  • pip install xlutils
  • 保存 excel 必须使用后缀名是 .xls 的,不是能是 .xlsx 的
#coding=utf-8

from xlutils.copy import copy
import xlrd

#打开要修改的excel
book = xlrd.open_workbook('d:\test.xls')
#copy()复制复制原来的excel进行编辑 new_book = copy(book)
#通过get_sheet(sheet_index)选择需要修改的sheet页 sheet = new_book.get_sheet(0)
#写入修改的内容,write(row_index,col_index,value)参数对应 行, 列, 值 sheet.write(0,1,'test')
#save(filename)保存修改后的excel,因为保存后的文件名第一步打开的文件名一致,所以保存的工作表会覆盖掉原来的工作表 new_book.save('d:\test.xls') """ #另存为test1.xls,会将之前的工作表复制后进行修改且另存到test1.xls中,原来的test.xls文件内容不变 new_book.save('d:\test1.xls') """
  • 写入 excel 数据操作封装
#coding=utf-8

from xlutils.copy import copy
import xlrd

def wrtel(excelpath,sheet_index,row_index,col_index,value):
    book = xlrd.open_workbook(excelpath)
    new_book = copy(book)
    sheet = new_book.get_sheet(sheet_index)
    sheet.write(row_index,col_index,value)
    new_book.save(excelpath)
#coding=utf-8

from WriteExcel import wrtel
import random

#调用wrtel方法创建课程表
date = [u"星期一",u"星期二",u"星期三",u"星期四",u"星期五"]
course = [u"语文",u"数学",u"英语",u"体育"]

colx = 0
for i in date:
    wrtel("C:UsersAdministratorDesktop\test.xls",0,0,colx,i)
    wrtel("C:UsersAdministratorDesktop\test.xls",0,1,colx,random.choice(course))
    wrtel("C:UsersAdministratorDesktop\test.xls",0,2,colx,random.choice(course))
    wrtel("C:UsersAdministratorDesktop\test.xls",0,3,colx,random.choice(course))
    wrtel("C:UsersAdministratorDesktop\test.xls",0,4,colx,random.choice(course))
    wrtel("C:UsersAdministratorDesktop\test.xls",0,5,colx,random.choice(course))
    colx += 1
原文地址:https://www.cnblogs.com/ZhengYing0813/p/11872971.html