0%

Python 使用 Xlrd/xlwt 操作 Excel

安装

sudo easy_install xlrd
sudo easy_install xlwt

xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。
其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已.

简单应用

import xlrd
data = xlrd.open_workbook('demo.xls') # 打开demo.xls
data.sheet_names()        # 获取xls文件中所有sheet的名称
table = data.sheets()[0]  # 获取xls文件第一个工作表
table = data.sheet_by_index(0)        # 通过索引获取xls文件第0个sheet
table = data.sheet_by_name(u'Sheet1') # 通过工作表名获取 sheet
# 获取行数和列数
nrows = table.nrows
ncols = table.ncols
# 获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i)
# 循环行,得到索引的列表
for rownum in range(table.nrows):
    print table.row_values(rownum)
# 获取单元格
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
# 简单的写入
row = 0
col = 0
ctype = 1 # 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
value = 'liluo'
xf = 0 # 扩展的格式化 (默认是0)
table.put_cell(row, col, ctype, value, xf)
table.cell(0,0) # 文本:u'lixiaoluo'
table.cell(0,0).value # 'lixiaoluo'
import xlwt
file = xlwt.Workbook()                # 注意这里的Workbook首字母是大写
table = file.add_sheet('sheet name')  # 新建一个sheet

table.write(0,0,'test')               # 写入数据table.write(行,列,value)

# 如果对一个单元格重复操作,会引发
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
# 所以在打开时加cell_overwrite_ok=True解决

table = file.add_sheet('sheet name',cell_overwrite_ok=True)
file.save('demo.xls')     # 保存文件

# 另外,使用style
style = xlwt.XFStyle()    # 初始化样式
font = xlwt.Font()        # 为样式创建字体
font.name = 'Times New Roman'
font.bold = True
style.font = font         #为样式设置字体
table.write(0, 0, 'some bold Times text', style) # 使用样式

根据格式化文本生成excel

# -*- coding: utf-8 -*-

import xlwt
import sys, os
import glob
import types
import linecache

title = []

sat_title = []

def create_defalut_xls():

    file_num = sys.argv[1]
    print file_num

    cwd = os.getcwd()
    xls_name = cwd + "/output/" + "default_strong.xls"
    print "defalut xls = %s" % (xls_name)

    sheetID = 0
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Satellites')

    style = xlwt.XFStyle()
    style.num_format_str = 'General'

    for i in range(0, len(title)):
        ws.write(sheetID, i, title[i])
        #ws.write(0, i, title[i], set_style('Times New Roman', 220, True))

    sheetID = 1;

    for i in range(0, int(file_num)):
        file = cwd + "/output/" + str(i) + ".txt"
        #print "file = %s" % (file)

        #if os.path.isfile(file):
        #    fp = open(file, "r")
        #    for line in fp:
        #        print line.strip('\n')
        #        print line.strip('\n').split(',')

        if os.path.isfile(file):
            line = len(open(file, "rU").readlines())
            print line
            sat_sheet_line = 0
            for k in range(1, line+1):
                content = linecache.getline(file, k).strip('\n')
                if k == 1:
                    name,longitude,id,direction = content.split(',')

                    sheetname = name.replace(' ', '_').replace('/', '_')
                    sheet = wb.add_sheet(sheetname)
                    #row = ['A', name, sheetname, int(longitude), 0, 0, 0, 0, 0, 0, int(direction), 0, 0]
                    row = ['A', name, sheetname, longitude, str(0), str(0), str(0), str(0), str(0), str(0), direction, str(0), str(0)]
                    #print row
                    for j in range(0, len(row)):
                        if j == 1:
                            #link = 'HYPERLINK("#'str(i)'!A1", "Link")'
                            #link = 'HYPERLINK("#'+ str(i) +'", "'+ name +'")'
                            link = 'HYPERLINK("#'+ sheetname + '!A1", "'+ name +'")'
                            ws.write(sheetID, j, xlwt.Formula(link))
                        else:
                            ws.write(sheetID, j, row[j], style)

                    for m in range(0, len(sat_title)):
                        sheet.write(sat_sheet_line, m, sat_title[m])
                    sat_sheet_line = sat_sheet_line + 1

                    sheetID = sheetID + 1
                else:
                    #print content
                    polar = content.split(',')[1]
                    fre = content.split(',')[4]
                    sym = content.split(',')[5]

                    #row = [' ', int(fre), int(sym), polar]
                    row = [' ', fre, sym, polar.strip(' ')]
                    for n in range(0, len(row)):
                        sheet.write(sat_sheet_line, n, row[n])
                    sat_sheet_line = sat_sheet_line + 1

    wb.save(xls_name)

if __name__ == "__main__":
    create_defalut_xls()

ref

  1. Working with Excel Files in Python
  2. Edit existing excel workbooks and sheets with xlrd and xlwt
  3. 使用第三方库xlutils来追加写Excel