只能新創建xls
# coding=utf-8
import xlwt
writebook = xlwt.Workbook() #打開excel
test= writebook.add_sheet('test') #添加一個名字叫test的sheet
test.write(0,1,'this is a test') #第0行第1列寫入字符串'this is a test'
writebook.save('testdata.xls') #一定要保存為xls,后綴是xlsx的文件打不開
后記:
要循環才能連續插入 不然只會插入最后一句
追加xls內容
首先要安裝三個模塊:xlrd,xlwt,xlutils
命令:pip install xlrd xlwt xlutils
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from xlrd import open_workbook
from xlutils.copy import copy
r_xls = open_workbook("test.xls") # 讀取excel文件
row = r_xls.sheets()[0].nrows # 獲取已有的行數
excel = copy(r_xls) # 將xlrd的對象轉化為xlwt的對象
table = excel.get_sheet(0) # 獲取要操作的sheet
#對excel表追加一行內容
table.write(row, 0, u'內容1') #括號內分別為行數、列數、內容
table.write(row, 1, u'內容2')
table.write(row, 2, u'內容3')
excel.save("test.xls") # 保存並覆蓋文件
參考 https://www.cnblogs.com/zhenwei66/p/8406201.html
讀取xls的方法: https://www.cnblogs.com/kaibindirver/p/9917158.html