首先导入库
import xlrd
import xlwt
import xlutils
from xlutils import copy #xlutils中导入copy
操作命令含义:
#sheet=book.sheet_by_index(0) #根据sheet编号来
#sheet=book.sheet_by_name('sheet1') #根据 sheet名称来
#print(sheet.nrows) #excel里面有多少行
#print(sheet.ncols) #excel里面有多少列
#print(sheet.cell(0,0).value) #获取第0行第0列的值
#print(sheet.row_values(0)) #获取到整行的内容
#print(sheet.col_values(0)) #获取到整列的内容
读excle
import xlrd
import xlwt
import xlutils
from xlutils import copy #xlutils中导入copy
book=xlrd.open_workbook('linux.xls')
sheet=book.sheet_by_index(0) #根据sheet编号来
for i in range(sheet.nrows): #循环获取每行的内容
print(sheet.row_values(i))
写入excle
import xlrd
import xlwt
import xlutils
from xlutils import copy #xlutils中导入copy
#得到excle对象
book=xlwt.Workbook()
sheet=book.add_sheet('sheet1')
#方法1,直接写入
sheet.write(10,2,"你好")#在10行2列写入你好,行和列都从0开始
#方法2,构造写入的内容,循环写入
listall=[
[1,'zhangsan'],
[2,'wangwu'],
[3,'lisi']
]
#写入excle
line=0 #控制的是行
for stu in listall:
col=0
for s in stu:
sheet.write(line,col,s)#写入excle
col+=1
line+=1
book.save('demo.xls')#保存,和本python文件同目录
结果:
修改excle:
import xlrd
import xlwt
import xlutils
from xlutils import copy #xlutils中导入copy
book=xlrd.open_workbook('demo.xls')
new_book=copy.copy(book)
#然后用xlutils里面的copy功能,复制一个excel
sheet=new_book.get_sheet(0) #获取sheet页
sheet.write(10,2,"helloworld")#修改为helloworld
new_book.save('demo.xls')
结果:
顺便说一下操作word:
from docx import Document
Doc = Document()
str1="天生我材必有用,千金散尽还复来"
Doc.add_paragraph(str1)
Doc.save("demo.docx")