1.使用到的 库 xlrd xlutils
pip install xxx // 注意安装的 python(2 的)
pip3 install xxx // 安装的是 python3
2.打开xls
book = xlrd.open_workbook('模版.xls',formatting_info=True)
//formatting_info=True 同时获取 excel 的内部样式的信息(包含合并单元格,颜色等)
3.获取表单
sheets=book.sheets()//获取所有表单
sheet_A37 = book.sheet_by_name('韩乡园') # 通过名字获取 某个 sheet
sheet_A37 = book.sheet_by_index(0) # 通过索引获取某个 sheet
4.获取行与列
rows = sheet_A37.nrows
cols = sheet_A37.ncols
5.获取cell 的值
cell = sheet_A37.cell_value(row,3)
5. 关于类型的判断
http://blog.csdn.net/gukesdo/article/details/7064868
type(cell) #查看 数据类型
if type(aaa) is types.IntType:#判断是否为 int数据类型
isinstance(cell,str) #判断是否为 str 数据类型
if cell.strip() != '': # 判断cell 的值不为 ‘’
6. 字典的 处理
list_cell = []
cell_target = {'row': row, 'col': 3, 'name': cell }
list_cell.append(cell_target)
item = item_target['val1'] # 获取值
item_target['val1'] = item # 修改值
7.写入数据
rb = xlrd.open_workbook('模版.xls',formatting_info=True)
wb = copy(rb)
ws = wb.get_sheet(3)
# 此处一定 得用get_sheet 来 获取 sheet,否则没有 write的功能 通过sheet_by_index sheet_by_name 就不行
for item in list_all:
ws.write(item['row'], item['col']+2, item['val1'])
ws.write(item['row'], item['col']+3, item['val2'])
wb.save('模版.xls')
补充1 查看 字符串是 str 还是 unicode
# 前提是 cell 是字符串,否则报错
print(cell.__class__) 打印字符串 是 str 还是 unicode
# 知道了此处是 str 还是 unicode ,就可以去 解决 打印中文乱码问题
# 当然,直接用python3 可以直接解决问题
http://in355hz.iteye.com/blog/1860787 http://wklken.me/posts/2013/08/31/python-extra-coding-intro.html
补充2 查看 某个文件的编码 格式 并改变 文件的编码格式
# chardet 需要安装
# f = open('YP03销售量排名.xls')
# data = f.read()
# print chardet.detect(data)
vim xxx (文件名)
esc 输入 :set fileencoding 回车,即可看到
esc 输入:set fileencoding=utf-8