码迷,mamicode.com
首页 > 编程语言 > 详细

Python种使用Excel

时间:2014-09-21 02:10:29      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   for   

  今天用到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(uSheet1)
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) # 使用样式

 

Python种使用Excel

标签:style   blog   http   color   io   os   使用   ar   for   

原文地址:http://www.cnblogs.com/zifenger/p/3983963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!