python(写入 excel 操作 xlwt 模块)
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的python(写入 excel 操作 xlwt 模块)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 残胃癌能不能吃鸡蛋羹
- 下一篇: JAVA基础系列:JDK目录结构