python 基础笔记十四

xlwt模块:只能写excel

xlrd模块:只能读excel

xlutils模块:只能修改excel

xlwt模块方法

1、xlwt.Workbook() :创建一个excel文件

2、.add_sheet('sheetName'):创建一个sheet页,命名为sheetName

3、.write(row,column,content):在第row行,第column列,写入内容content

4、.save('stu.xls'):保存文件

 1 import xlwt
 2 #写excle
 3 book = xlwt.Workbook()   #创建一个excel文件
 4 sheet = book.add_sheet('sheet1')  #创建一个sheet页,命名为sheet1
 5 sheet.write(0,0,'id')         #第1行 第1列
 6 sheet.write(0,1,'username')  #第1行 第2列
 7 sheet.write(0,2,'password')  #第1行 第3列
 8 
 9 sheet.write(1,0,'1')          #第2行 第1列
10 sheet.write(1,1,'wuxuewen1') #第2行 第2列
11 sheet.write(1,2,'123456')    #第2行 第3列
12 
13 book.save('stu.xls')         #保存文档,后缀名只能是.xls,微软软件识别不了.xlsx
View Code

 循环写入文件:

 1 import xlwt
 2 #写excle
 3 book = xlwt.Workbook()   #创建一个excel文件
 4 sheet = book.add_sheet('sheet1')  #创建一个sheet页,命名为sheet1
 5 
 6 sheet.write(0,0,'id')
 7 sheet.write(0,1,'username')
 8 sheet.write(0,2,'password')
 9 
10 stus = [
11     [1,'wxw1','123456'],
12     [2,'wxw2','123456'],
13     [3,'wxw3','123456'],
14     [4,'wxw4','123456'],
15     [5,'wxw5','123456'],
16     [6,'wxw6','123456'],
17     [7,'wxw7','123456'],
18     [8,'wxw8','123456'],
19     [9,'wxw9','123456']
20 ]
21 
22 row = 1  #控制行
23 for stu in stus:
24     col = 0  #控制列
25     for s in stu:
26         sheet.write(row,col,s)
27         col += 1
28     row += 1
29 
30 book.save('stu.xls')         #保存文档,后缀名只能是.xls,微软软件识别不了.xlsx
View Code

xlrd模块方法:

1、xlrd.open_workbook(fileName):打开excel文件

2、.sheet_by_index(n):获取第几个sheet页

3、.sheet_by_name(sheetName) :获得名为sheetName的sheet页

4、.nrows:excel里面有多少行

5、.ncols:excel里面有多少列

6、.cell(row,col).value:获取到指定单元格的内容

7、.row_values(n):获取到第n行整行的内容

8、.col_values(n):获取到第n列整列的内容

 1 import xlrd
 2 #读excel
 3 book = xlrd.open_workbook('stu.xls')
 4 sheet = book.sheet_by_index(0) #获取第几个sheet页
 5 # sheet = book.sheet_by_name('sheet1') #获得名为sheet1的sheet页
 6 
 7 print(sheet.nrows) #excel里面有多少行
 8 print(sheet.ncols) #excel里面有多少列
 9 
10 print(sheet.cell(0,1).value) #获取到指定单元格的内容
11 
12 print(sheet.row_values(1)) #获取到第二行整行的内容
13 print(sheet.col_values(1)) #获取到第二列整列的内容
14 
15 #循环获取每行的内容
16 for i in range(sheet.nrows):
17     print(sheet.row_values(i))
View Code

 

xlutils模块方法:

1、copy.copy(book) :用xlutils里面的copy功能,复制一个excel

2、.get_sheet(n):获取第n个标签页

3、.write(row,col,content):单元格写入内容

4、.save('fileName'):保存文件

 1 #修改excel
 2 import xlrd
 3 from xlutils import copy
 4 
 5 book = xlrd.open_workbook('stu.xls') #先用xlrd打开一个excel
 6 new_book = copy.copy(book) #然后用xlutils里面的copy功能,复制一个excel
 7 
 8 sheet = new_book.get_sheet(0) #获取sheet页
 9 sheet.write(0,1,'账号')
10 new_book.save('stu.xls') #保存的名字已存在则会替换源文件内容,如果不一致则会新建一个文件
View Code
原文地址:https://www.cnblogs.com/wu-xw/p/9704924.html