---
title: "用xlrd和xlwt操作Excel文档"
author: "finux"
date: "2010-06-26T22:04:51Z"
tags: []
categories: ["编程语言"]
slug: "xlrd-xlwt-excel"
draft: false
lastmod: "2010-06-26T22:06:44Z"
id: 700033
url: "https://finux.iteye.com/blog/700033"
---

工作当中经常要操作excel文档，有些完全是纯粹的重复劳动。在我的工作中就遇到这样一个需求：  
1\. 存在两个excel文档（source.xls/target.xls），列数据是一致的  
2\. 文档source.xls的数据来源于target.xls，经常要修改source.xls文档中的数据，但是两个文档中有一列（COLUMN\_INDEX）的数据只要存在就会保持不变  
3\. 文档target.xls已经存在一个office控件，可以从某个数据库读取数据，写回该文档  
4\. 数据库中的数据每天都会更新  
5\. 需要经常更新source.xls，将不存在该文档但存在于target.xls的数据copy过来，依据列（COLUMN\_INDEX）

需求出来了，google了下，发现可以用xlrd/xlwt来操作excel文档，模块名取得挺有意思哦，根据名字看，显示xlrd用来读excel，xlwt用来写罗。至于为啥读和写会是不同的第三方包，或者是excel的数据存取比较复杂吧。

xlrd模块api文档：http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Cell-class

下面是Python实现：

```
#!/usr/bin/env python
#coding=utf-8

'''
created by 2010-6-26
author: py_zhu
'''

import xlrd
import xlwt

SOURCE_FILE = "source.xls"
TARGET_FILE = "target.xls"
RESULT_FILE = "result.xls"

COLUMN_INDEX = 3

def readColumnIndex():
	columnIndex = -1;
	#read column index(from config file)
	columnIndex = COLUMN_INDEX
	return columnIndex

def calc():
	source = set([])
	target = dict()
	columnIndex = readColumnIndex()

	sheet = xlrd.open_workbook(SOURCE_FILE).sheet_by_index(0)
	for i in range(sheet.nrows):
		source.add(sheet.cell_value(i, columnIndex))
	
	sheet = xlrd.open_workbook(TARGET_FILE).sheet_by_index(0)
	for i in range(sheet.nrows):
		#(cell_value, rowIndex)
		target.put(sheet.cell_value(i, columnIndex), i)
	
	for i in source:
		if i in target:
			del target[i]
	
	#create new execel file
	workbook = xlwt.Workbook(encoding = 'utf-8')
	resultSheet = workbook.add_sheet('result_sheet')
	resultRows = target.values()
	for i in range(len(resultRows)):
		for j in range(sheet.ncols):
			resultSheet.write(i, j, sheet.cell_value(resultRows[i], j))
	workbook.save(RESULT_FILE)
	
def main():
	calc()

if __name__ == '__main__':
	main()
```

 

[source code](https://pyzhu.googlecode.com/svn/trunk/python/MyExcelTool.py)