Python中使用第三方库xlrd来写入Excel文件示例

WBOY
Release: 2016-06-10 15:16:14
Original
1605 people have browsed it

继上一篇文章使用xlrd来读Excel之后,这一篇文章就来介绍下,如何来写Excel,写Excel我们需要使用第三方库xlwt,和xlrd一样,xlrd表示read xls,xlwt表示write xls,同样目前版本只支持97-03版本的Excel。xlwt下载:xlwt 0.7.4

安装xlwt

安装方式一样是python setup.py install就可以了,或者直接解压到你的工程目录中。

API介绍

获取一个xls实例

复制代码 代码如下:

xls = ExcelWrite.Workbook()

添加一个sheet
复制代码 代码如下:

sheet = xls.add_sheet("Sheet1")

向sheet中写入数据
复制代码 代码如下:

sheet.write(row_index, col_index, value)

保存生成xls
复制代码 代码如下:

xls.save(file_name)

使用xlwt
复制代码 代码如下:

# -*- coding: utf-8 -*- 
'''  
Created on 2012-12-14  
 
@author:  walfred 
@module: XLRDPkg.write  
@description: 
'''   
 
import xlwt as ExcelWrite 
 
def writeXLS(file_name): 
    value = [["name", "jim", "hmm", "lilei"], ["sex", "man", "woman", "man"], ["age", 19, 24, 24], ["country", "USA", "CHN", "CHN"]]  
    xls = ExcelWrite.Workbook() 
    sheet = xls.add_sheet("Sheet1") 
 
    for i in range(0, 4): 
        for j in range(0, len(value)): 
            sheet.write(j, i, value[i][j]) 
 
    xls.save(file_name) 
 
if __name__ == "__main__": 
    writeXLS("./test_write.xls");

当然这只是简单的介绍下如何使用xlwt,更多功能个API需要读者自行从下载包中学习,比如设置格式、超链接、公式等。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!