Python操作Excel

1. 读取Excel

安装xlrd模块,下载地址http://pypi.python.org/pypi/xlrd

安装方法,解压后进入模块目录,使用python setup.py install命令安装。(前提是已经安装了Python)

1) 导入模块

import xlrd

2) 打开Excel文件读取数据

data = xlrd.open_workbook('excelFile.xls')

3) 使用技巧

#获取一个工作表
table = data.sheets()[0]                 #通过索引顺序获取
table = data.sheet_by_index(0)           #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')    #通过名称获取
 
#获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i)
 
#获取行数和列数
nrows = table.nrows
ncols = table.ncols
       
#循环行列表数据
for i in range(nrows):
    print table.row_values(i)
 
#单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
 
#使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value

2. 写入Excel

安装xlwt模块,下载地址https://pypi.python.org/pypi/xlwt/,安装方法同上。
 
简单例子:
#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import xlwt 

file = xlwt.Workbook(encoding = 'utf-8') 
table = file.add_sheet('hello', cell_overwrite_ok = True) 

table.write(1, 1, '测试') 
file.save('demo.xls')

设置字体:

style = xlwt.XFStyle()
font = xlwt.Font()
font.name = 'SimSun'    # 指定“宋体”
style.font = font       

table.write(1, 1, '测试', style) # 使用 style
原文地址:https://www.cnblogs.com/Xavierr/p/3158057.html