---
title: "Python修改Excel文件"
author: "booby325"
date: "2012-12-27T22:51:03Z"
tags: []
categories: ["编程语言"]
slug: "python-excel"
draft: false
lastmod: "2012-12-27T22:54:58Z"
id: 1756080
url: "https://booby325.iteye.com/blog/1756080"
---

Python Excel：[http://www.python-excel.org/](http://www.python-excel.org/)  
xlrd：[Download](http://pypi.python.org/pypi/xlrd) | [Documentation](https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html)  
xlwt: [Download](http://pypi.python.org/pypi/xlwt) | [Documentation](https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html) | [Examples](https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/examples/)  
xlutils: [Download](http://pypi.python.org/pypi/xlutils) | [Documentation](https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/)

python-excel：[http://www.simplistix.co.uk/presentations/python-excel.pdf](http://www.simplistix.co.uk/presentations/python-excel.pdf "Download")

 

 

[Python](http://www.python.org/)中一般使用[xlrd](http://pypi.python.org/pypi/xlrd)（e**x**ce**l** **r**ea**d**）来读取Excel文件，使用[xlwt](http://pypi.python.org/pypi/xlwt)（e**x**ce**l** **w**ri**t**e）来生成Excel文件（可以控制Excel中单元格的格式），需要注意的是，用[xlrd](http://pypi.python.org/pypi/xlrd)读取excel是不能对其进行操作的：xlrd.open\_workbook()方法返回xlrd.Book类型，是只读的，不能对其进行操作。而xlwt.Workbook()返回的xlwt.Workbook类型的save(filepath)方法可以保存excel文件。

因此对于读取和生成Excel文件都非常容易处理，但是对于已经存在的Excel文件进行修改就比较麻烦了。不过，还有一个[xlutils](http://pypi.python.org/pypi/xlutils)（依赖于xlrd和xlwt）提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已

 

xlrd:

 

```
# encoding : utf-8       #设置编码方式
import xlrd                    #导入xlrd模块

#打开指定文件路径的excel文件
xlsfile = r'D:\AutoPlan\apisnew.xls' 
book = xlrd.open_workbook(xlsfile)     #获得excel的book对象

#获取sheet对象，方法有2种：
sheet_name=book.sheet_names()[0]          #获得指定索引的sheet名字
print sheet_name
sheet1=book.sheet_by_name(sheet_name)  #通过sheet名字来获取，当然如果你知道sheet名字了可以直接指定
sheet0=book.sheet_by_index(0)     #通过sheet索引获得sheet对象

#获取行数和列数：
nrows = sheet.nrows    #行总数
ncols = sheet.ncols   #列总数

#获得指定行、列的值，返回对象为一个值列表
row_data = sheet.row_values(0)   #获得第1行的数据列表
col_data = sheet.col_values(0)  #获得第一列的数据列表，然后就可以迭代里面的数据了

#通过cell的位置坐标获得指定cell的值
cell_value1 = sheet.cell_value(0,1)  ##只有cell的值内容，如：http://xxx.xxx.xxx.xxx:8850/2/photos/square/
print cell_value1
cell_value2 = sheet.cell(0,1) ##除了cell值内容外还有附加属性，如：text:u'http://xxx.xxx.xxx.xxx:8850/2/photos/square/'
print cell_value2
```

 

xlwt:

 

Django中导出：

```
import xlwt
# export excel to file
def export_excel(request):
    import pdb;pdb.set_trace()
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=detect_myspace.xls'    
    wb = xlwt.Workbook()
    ws = wb.add_sheet('Sheetname')
    
    ws.write(0, 0, 'Firstname')
    ws.write(0, 1, 'Surname')
    ws.write(1, 0, 'Hans')
    ws.write(1, 1, 'Muster')

    wb.save(response)
    return response
```