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:\Users\Administrator\Desktop\\test.xls",0,0,colx,i)
    wrtel("C:\Users\Administrator\Desktop\\test.xls",0,1,colx,random.choice(course))
    wrtel("C:\Users\Administrator\Desktop\\test.xls",0,2,colx,random.choice(course))
    wrtel("C:\Users\Administrator\Desktop\\test.xls",0,3,colx,random.choice(course))
    wrtel("C:\Users\Administrator\Desktop\\test.xls",0,4,colx,random.choice(course))
    wrtel("C:\Users\Administrator\Desktop\\test.xls",0,5,colx,random.choice(course))
    colx += 1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM