python操做Excel的幾種方式

Python對Excel的讀寫主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter幾種。html

1.xlrd主要是用來讀取excel文件python

import xlrd
data = xlrd.open_workbook('abcd.xls') # 打開xls文件
table = data.sheets()[0] # 打開第一張表
nrows = table.nrows # 獲取表的行數
for i in range(nrows): # 循環逐行打印
    if i == 0:# 跳過第一行
        continue
    print (table.row_values(i)[:13]) # 取前十三列

  示例2:excel

#coding=utf-8
#######################################################
#filename:test_xlrd.py
#author:defias
#date:xxxx-xx-xx
#function:讀excel文件中的數據
#######################################################
import xlrd
#打開一個workbook
workbook = xlrd.open_workbook('E:\\Code\\Python\\testdata.xls')
#抓取全部sheet頁的名稱
worksheets = workbook.sheet_names()
print('worksheets is %s' %worksheets)
#定位到sheet1
worksheet1 = workbook.sheet_by_name(u'Sheet1')
"""
#經過索引順序獲取
worksheet1 = workbook.sheets()[0]
#或
worksheet1 = workbook.sheet_by_index(0)
"""
"""
#遍歷全部sheet對象
for worksheet_name in worksheets:
worksheet = workbook.sheet_by_name(worksheet_name)
"""
#遍歷sheet1中全部行row
num_rows = worksheet1.nrows
for curr_row in range(num_rows):
row = worksheet1.row_values(curr_row)
print('row%s is %s' %(curr_row,row))
#遍歷sheet1中全部列col
num_cols = worksheet1.ncols
for curr_col in range(num_cols):
col = worksheet1.col_values(curr_col)
print('col%s is %s' %(curr_col,col))
#遍歷sheet1中全部單元格cell
for rown in range(num_rows):
for coln in range(num_cols):
cell = worksheet1.cell_value(rown,coln)
print cell
"""
#其餘寫法:
cell = worksheet1.cell(rown,coln).value
print cell
#或
cell = worksheet1.row(rown)[coln].value
print cell
#或
cell = worksheet1.col(coln)[rown].value
print cell
#獲取單元格中值的類型,類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
cell_type = worksheet1.cell_type(rown,coln)
print cell_type
"""

 更多詳細使用:http://www.javashuo.com/article/p-zelkjhlz-ct.html htm

 

2.xlwt主要是用來寫excel文件對象

import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
sheet.write(0,1,'test text')#第0行第一列寫入內容
wbk.save('test.xls')

 

3.xlutils結合xlrd能夠達到修改excel文件目的blog

import xlrd
from xlutils.copy import copy
workbook = xlrd.open_workbook(u'有趣裝逼每日數據及趨勢.xls')
workbooknew = copy(workbook)
ws = workbooknew.get_sheet(0)
ws.write(3, 0, 'changed!')
workbooknew.save(u'有趣裝逼每日數據及趨勢copy.xls')

  

4.openpyxl能夠對excel文件進行讀寫操做索引

from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.writer.excel import ExcelWriter  

workbook_ = load_workbook(u"新歌檢索失敗1477881109469.xlsx")
sheetnames =workbook_.get_sheet_names() #得到表單名字
print sheetnames
sheet = workbook_.get_sheet_by_name(sheetnames[0])
print sheet.cell(row=3,column=3).value
sheet['A1'] = '47' 
workbook_.save(u"新歌檢索失敗1477881109469_new.xlsx")  
wb = Workbook()
ws = wb.active
ws['A1'] = 4
wb.save("新歌檢索失敗.xlsx") 

  示例2:utf-8

import openpyxl
# 新建文件
workbook = openpyxl.Workbook() 
# 寫入文件
sheet = workbook.activesheet['A1']='A1'
# 保存文件 
workbook.save('test.xlsx')

  

5.xlsxwriter能夠寫excel文件並加上圖表get

import xlsxwriter

def get_chart(series):
    chart = workbook.add_chart({'type': 'line'})
    for ses in series:
        name = ses["name"]
        values = ses["values"]
        chart.add_series({
            'name': name,
            'categories': 'A2:A10',
            'values':values
        })
    chart.set_size({'width': 700, 'height': 350})
    return chart 

if __name__ == '__main__':
    workbook = xlsxwriter.Workbook(u'H5應用中心關鍵數據及趨勢.xlsx') 
    worksheet = workbook.add_worksheet(u"每日PV,UV")
    headings = ['日期', '平均值']
    worksheet.write_row('A1', headings)
    index=0
    for row in range(1,10):
        for com in [0,1]:
            worksheet.write(row,com,index)
            index+=1
    series = [{"name":"平均值","values":"B2:B10"}]
    chart = get_chart(series)
    chart.set_title ({'name': '每日頁面分享數據'})  
    worksheet.insert_chart('H7', chart)
    workbook.close() 

openpyxl 

  示例2:string

import xlsxwriter as xw
#新建excel
workbook  = xw.Workbook('myexcel.xlsx')
#新建工做薄
worksheet = workbook.add_worksheet()
#寫入數據
worksheet.wirte('A1',1)
#關閉保存
workbook.close()

 合併表格實例:

#coding:utf-8
import xlsxwriter
import xlrd
#新建excel
workbook  = xlsxwriter.Workbook('廣東.xlsx')
#新建工做薄
worksheet = workbook.add_worksheet()

count = 1
worksheet.write("A%s"%count,"公司名稱")
worksheet.write("B%s"%count,"法人")
worksheet.write("C%s"%count,"電話")
worksheet.write("D%s"%count,"註冊資金")
worksheet.write("E%s"%count,"註冊時間")
count+=1
for i in range(1,153):
    data = xlrd.open_workbook('ah (%s).xls'%i) # 打開xls文件
    table = data.sheets()[0] # 打開第一張表
    nrows = table.nrows # 獲取表的行數
    for i in range(nrows): # 循環逐行打印
        if i == 0:# 跳過第一行
            continue
        # print (table.row_values(i)[:5]) # 取前十三列
        print(count,table.row_values(i)[:5][0])

        #寫入數據
        #設定第一列(A)寬度爲20像素 A:E表示從A到E
        worksheet.set_column('A:A',30)
        worksheet.set_column('B:E',20)
        worksheet.write("A%s"%count,table.row_values(i)[:5][0])
        worksheet.write("B%s"%count,table.row_values(i)[:5][1])
        worksheet.write("C%s"%count,table.row_values(i)[:5][2])
        worksheet.write("D%s"%count,table.row_values(i)[:5][3])
        worksheet.write("E%s"%count,table.row_values(i)[:5][4])
        count+=1

#關閉保存
workbook.close()
相關文章
相關標籤/搜索