啊峰哥

打开和写入excel文件

一.使用win32读取excel内容

# -*- coding: utf-8 -*-
from win32com import client as wc
def open_excel():
    excel = wc.Dispatch('EXCEL.Application')                 #使用excel程序   
    excel.Visible = 0                                        #不打开excel界面
    my_excel = excel.Workbooks.Open(u'新建表格.xls')          #指定表格路径

    my_sheet = my_excel.Sheets('Sheet1')                     #打开表格中的sheet1,根据实际情况而定

    for i in range(my_sheet.UsedRange.Rows.Count):           #遍历sheet1中的表格列数
        for j in range(my_sheet.UsedRange.Columns.Count):    #遍历sheet1中的表格行数
            print my_sheet.Cells(i + 1, j + 1).Value         #读取相应的坐标表格值,并打印
    my_excel.Close()                                         #关闭表格
    excel.Quit()
open_excel()

 

二.使用xlrd读取excel内容(比第一种方法快很多)

# -*- coding: utf-8 -*-
from xlrd import open_workbook

def open_excel2():                                                       #快很多
    wb = open_workbook(u'新建表格.xls')                                   #指定路径
    for s in wb.sheets():                                                #遍历sheet表
        for row in range(s.nrows):                                       #遍历列
            for col in range(s.ncols):                                   #遍历行
                print s.cell(row,col).value                              #打印值

open_excel()

 三.使用xlwt写入表格

# -*- coding: utf-8 -*-
from xlwt import *

lists = ['a','b','c']
n = 0                                                    #第一列

def add_excel(n):
    filename = u'新建列表.xls'
    file = Workbook(encoding='utf-8')                    #指定file以utf-8的格式打开
    sheet1 = file.add_sheet('sheet1')                    #写入sheet1
    for m in range(len(lists)):
        sheet1.write(m,n,lists[m])                       #指定坐标(m,n)写入内容
    file.save(filename)                                  #保存excel文件

add_excel(n)

 

posted on 2017-09-23 17:30  啊峰哥  阅读(444)  评论(0编辑  收藏  举报

导航