首页 > 技术文章 > Python种使用Excel

zifenger 2014-09-20 23:34 原文

  今天用到Excel的相关操作,看了一些资料,借此为自己保存一些用法。

  参考资料:

  python excel 的相关操作

  python操作excel之xlrd  

      python操作Excel读写--使用xlrd

 

 1 # -*- coding: UTF-8 -*-
 2 
 3 import xlrd  # 导入xlrd模块 
 4 
 5 # 打开指定文件路径的excel文件,获得excel的book对象
 6 book = xlrd.open_workbook('MIT.xls')
 7 
 8 # 查看文件中包含sheet的名称
 9 sh_names = book.sheet_names()
10 
11 # 得到第一个工作表,或者通过索引顺序 或 工作表名称
12 sheet = book.sheets()[0]
13 sheet = book.sheet_by_index(0)
14 sheet = book.sheet_by_name(u'Sheet1')
15 
16 # 获取行数和列数:   
17 nrows = sheet.nrows    # 行总数 
18 ncols = sheet.ncols   # 列总数
19 
20 # 循环行,得到索引的列表
21 for rownum in xrange(sheet.nrows):
22     print sheet.row_values(rownum)
23 
24 # 获取整行和整列的值(数组)
25 row_data = sheet.row_values(0)   # 获得第1行的数据列表 
26 col_data = sheet.col_values(0)   # 获得第一列的数据列表
27 
28 # 单元格(索引获取)
29 cell_A1 = sheet.cell(0,0).value
30 cell_C4 = sheet.cell(3,2).value
31 
32 # 分别使用行列索引
33 cell_A1 = sheet.row(0)[0].value
34 cell_A2 = sheet.col(0)[1].value

 

 1 # -*- coding: UTF-8 -*-
 2 
 3 import xlwt  # 导入xlwt模块
 4 
 5 # 新建一个excel文件
 6 book = xlwt.Workbook(encoding='utf-8', style_compression=0)
 7 
 8 # 新建一个sheet
 9 sheet = book.add_sheet('sheet1', cell_overwrite_ok=True) ##第二参数用于确认同一个cell单元是否可以重设值。
10 
11 # 写入数据sheet.write(行,列,value)
12 sheet.write(0,0,'test')
13 ## 重新设置,需要cell_overwrite_ok=True,否则引发异常
14 sheet.write(0,0,'this should overwrite') 
15 
16 # 保存文件
17 book.save('demo.xls')
18 
19 # 使用style
20 style = xlwt.XFStyle() #初始化样式
21 font = xlwt.Font() #为样式创建字体
22 font.name = 'Times New Roman'
23 font.bold = True
24 style.font = font #为样式设置字体
25 sheet.write(0, 0, 'some bold Times text', style) # 使用样式

 

推荐阅读