21天学Python --- 打卡6:Python操作Excel

在这里插入图片描述

21天学Python --- 打卡6:Python操作Excel

    • 1.Required plugins
      • 1.1 Plugin
      • 1.2 Notice
    • 2.Demo
      • 2.1 Create Excel
      • 2.2 xlrd主要是用来读取excel文件
      • 2.3 xlwt主要是用来写excel文件
      • 2.4 xlutils结合xlrd可以达到修改excel文件目的
      • 2.5 openpyxl可以对excel文件进行读写操作
      • 2.6 xlsxwriter可以写excel文件并加上图表


21天学Python --- 打卡6:Python操作Excel_第1张图片

1.Required plugins

1.1 Plugin

Python对Excel的读写主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter几种。

  • xlrd - 读excel文件
  • xlwt - 写excel文件,这个不能修改已有的excel文件,只能写新的文件
  • xlutils - 修改excel文件,其实就是通过xlrd拷贝一份记录,再进行修改
  • openpyxl - 可以对excel文件进行读写操作
  • xlsxwriter - 可以写excel文件并加上图表

sudo pip3 install xlwt -i https://pypi.tuna.tsinghua.edu.cn/simple
sudo pip3 list # 查看下载结果

1.2 Notice

  • python读取excel的日期和时间时
    1. 表格内容是2019/5/13,python读到的值是43606.0,该值为从日期减1899/12/30得到的天数
    2.表格内容是9:00:00,python读到的值是0.375,该值为时间过了一天的比例,即9/24
    3.表格内容是2019/5/13 9:00:00,python读到的值是43598.375,日期和时间可以直接相加
  • python读取excel的数字时,如员工编号为181129,最后结果是181129.0,非整数
  • 调用save函数保存新的excel文件时,后缀名必须是.xls

2.Demo

2.1 Create Excel

#coding:utf-8
#!/usr/local/python3/bin/python3
import xlwt

workbook = xlwt.Workbook(encoding='utf-8')

worksheet = workbook.add_sheet('Python')
workbook.save(str("createExcel.xls"))

# ===Execute===
python3 demo.py 

2.2 xlrd主要是用来读取excel文件

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])

 # ===Execute===
python3 demo.py    

2.3 xlwt主要是用来写excel文件

#===========写入内容==============
#coding:utf-8
#!/usr/local/python3/bin/python3
import xlwt

workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Python')

# 在单元格中写入数据
worksheet.write(0, 0, "hello")
worksheet.write(0, 1, "this is")
worksheet.write(0, 2, "first")
worksheet.write(1, 1, "pythob demo")

workbook.save(str("demo.xls"))


 # ===Execute===
python3 demo.py    
#===========合并单元格==============
#coding:utf-8
#!/usr/local/python3/bin/python3
import xlwt


workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Python')
worksheet.write(0, 0, "hello")
worksheet.write(0, 1, "this is")
worksheet.write(0, 2, "first")
worksheet.write(1, 1, "pythob demo")

worksheet.write_merge(1, 1, 0, 2, "demo")
workbook.save(str("demo.xls"))

 # ===Execute===
python3 demo.py    
#===========单元格内容居中对齐==============
#coding:utf-8
#!/usr/local/python3/bin/python3
import xlwt


workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Python')
head_style = xlwt.XFStyle()

# 设置单元格对齐方式
ahead_lignment = xlwt.Alignment()  # 对齐初始化
ahead_lignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平居中
ahead_lignment.vert = xlwt.Alignment.VERT_CENTER  # 垂直居中
head_style.alignment = ahead_lignment  # 样式重载

worksheet.write(0, 0, "hello")
worksheet.write(0, 1, "this is")
worksheet.write(0, 2, "first")
worksheet.write(1, 1, "pythob demo")

worksheet.write_merge(1, 1, 0, 2, "demo")
workbook.save(str("demo.xls"))
#===========修改字体和颜色==============
#coding:utf-8
#!/usr/local/python3/bin/python3
import xlwt

workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Python')
head_style = xlwt.XFStyle()

# 创建字体
head_font = xlwt.Font()  # 字体初始化
head_font.name = '楷体'  # 字体
head_font.height = 300  # 大小
head_font.colour_index = 2  # 红色
head_style.font = head_font  # 样式重载

# 设置单元格对齐方式
ahead_lignment = xlwt.Alignment()  # 对齐初始化
ahead_lignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平居中
ahead_lignment.vert = xlwt.Alignment.VERT_CENTER  # 垂直居中
head_style.alignment = ahead_lignment  # 样式重载

worksheet.write(0, 0, "hello")
worksheet.write(0, 1, "this is")
worksheet.write(0, 2, "first")
worksheet.write(1, 1, "pythob demo")

worksheet.write_merge(1, 1, 0, 2, "demo")
workbook.save(str("demo.xls"))

2.4 xlutils结合xlrd可以达到修改excel文件目的

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')

 # ===Execute===
python3 demo.py    

2.5 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") 

 # ===Execute===
python3 demo.py    
import openpyxl

# 新建文件
workbook = openpyxl.Workbook()

# 写入文件
sheet = workbook.activesheet['A1']='A1'

# 保存文件
workbook.save('test.xlsx')

2.6 xlsxwriter可以写excel文件并加上图表

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    
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表示从AE
        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()

你可能感兴趣的:(Python,python)