Python办公自动化EXCEL操作

1.1 read.py

  • pip install xlrd
import xlrd

def print_type(x):
    print(type(x))

xlsx = xlrd.open_workbook(
    'G:/0.Download/BaiduYun下载/12 用Python自动办公,做职场高手(完结)/01.文件/【12.20更新课程代码】用Python自动办公做职场高手/CourseCode/Chapter1/S1-1-1/LessonCode/7月下旬入库表.xlsx')

# 通过sheet名查找:xlsx.sheet_by_name("7月下旬入库表")
# 通过索引查找:xlsx.sheet_by_index(3)
table = xlsx.sheet_by_index(0)

# 获取表格值
# table.cell_value(1, 2)
# print(table.cell(1, 2).value)
# print(table.row(1)[2].value)
print(table.cell_value(0, 0))

# 获取所有sheet名字:xlsx.sheet_names()
for i in xlsx.sheet_names():
    table = xlsx.sheet_by_name(i)
    print(table.cell_value(3, 3))

# 获取sheet数量:xlsx.nsheets()
for i in range(0, xlsx.nsheets):
    table = xlsx.sheet_by_index(i)
    print(table.cell_value(0, 0))

1.1 write.py

  • pip install xlwt
import xlwt
new_workbook = xlwt.Workbook()
worksheet = new_workbook.add_sheet('new_test')
worksheet.write(0, 0, 'test')
new_workbook.save('d:/test.xls')

1.1 exercise.py

  • pip install xlsxwriter
#1、2星答案
# import xlrd,xlwt
# xlsx = xlrd.open_workbook('d:/7月下旬入库表.xlsx')
# new_workbook = xlwt.Workbook()
# worksheet = new_workbook.add_sheet('new_test')
# table = xlsx.sheet_by_index(0)
# for i in range(0,table.nrows):
#     for j in range(0,table.ncols):
#         print(table.cell_value(i, j))
#         worksheet.write(i, j, table.cell_value(i, j))
# new_workbook.save('d:/test.xls')

#3星答案
import xlrd,xlsxwriter
xlsx = xlrd.open_workbook('d:/7月下旬入库表.xlsx')
new_workbook = xlsxwriter.Workbook('d:/test.xlsx')
worksheet = new_workbook.add_worksheet()
table = xlsx.sheet_by_index(0)
for i in range(0,table.nrows):
    for j in range(0,table.ncols):
        print(table.cell_value(i, j))
        worksheet.write(i, j, table.cell_value(i, j))
new_workbook.close()

1.2 templete.py

  • pip install xlutils
from xlutils.copy import copy
import xlrd
import xlwt

tem_excel = xlrd.open_workbook('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-2/LessonCode/日统计.xls', formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()
font.name = '微软雅黑'
font.bold = True
font.height = 360
style.font = font

borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders

alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style.alignment = alignment

"""
new_sheet.write(2, 1, 12)
new_sheet.write(3, 1, 18)
new_sheet.write(4, 1, 19)
new_sheet.write(5, 1, 15)
"""

new_sheet.write(2, 1, 12, style)
new_sheet.write(3, 1, 18, style)
new_sheet.write(4, 1, 19, style)
new_sheet.write(5, 1, 15, style)


new_excel.save('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-2/LessonCode/填写.xls')

1.2 exercise.py

from xlutils.copy import copy
import xlrd
import xlwt

tem_excel = xlrd.open_workbook('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-2/PracticeAnswer/日统计.xls', formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()
font.name = '宋体'
font.bold = True
font.height = 360
style.font = font

borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders

alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_LEFT
alignment.vert = xlwt.Alignment.VERT_TOP
style.alignment = alignment

style_red = xlwt.XFStyle()

font_red = xlwt.Font()
font_red.name = '宋体'
font_red.bold = True
font_red.height = 360
font_red.colour_index = 2
style_red.font = font_red

borders_red = xlwt.Borders()
borders_red.top = xlwt.Borders.THIN
borders_red.bottom = xlwt.Borders.THIN
borders_red.left = xlwt.Borders.THIN
borders_red.right = xlwt.Borders.THIN
style_red.borders = borders_red

alignment_red = xlwt.Alignment()
alignment_red.horz = xlwt.Alignment.HORZ_LEFT
alignment_red.vert = xlwt.Alignment.VERT_TOP
style_red.alignment = alignment_red

style_lishu18 = xlwt.XFStyle()

font_lishu18 = xlwt.Font()
font_lishu18.name = '隶书'
font_lishu18.bold = True
font_lishu18.height = 360
style_lishu18.font = font_lishu18

borders_lishu18 = xlwt.Borders()
borders_lishu18.top = xlwt.Borders.THIN
borders_lishu18.bottom = xlwt.Borders.THIN
borders_lishu18.left = xlwt.Borders.THIN
borders_lishu18.right = xlwt.Borders.THIN
style_lishu18.borders = borders_lishu18

alignment_lishu18 = xlwt.Alignment()
alignment_lishu18.horz = xlwt.Alignment.HORZ_CENTER
alignment_lishu18.vert = xlwt.Alignment.VERT_CENTER
style_lishu18.alignment = alignment_lishu18

style_lishu22 = xlwt.XFStyle()

font_lishu22 = xlwt.Font()
font_lishu22.name = '隶书'
font_lishu22.bold = True
font_lishu22.height = 440
style_lishu22.font = font_lishu22

borders_lishu22 = xlwt.Borders()
borders_lishu22.top = xlwt.Borders.THIN
borders_lishu22.bottom = xlwt.Borders.THIN
borders_lishu22.left = xlwt.Borders.THIN
borders_lishu22.right = xlwt.Borders.THIN
style_lishu22.borders = borders_lishu22

alignment_lishu22 = xlwt.Alignment()
alignment_lishu22.horz = xlwt.Alignment.HORZ_CENTER
alignment_lishu22.vert = xlwt.Alignment.VERT_CENTER
style_lishu22.alignment = alignment_lishu22

zhangsan_num = int(input('请输入张三粮配入库量:'))
lisi_num = int(input('请输入李四粮食入库量:'))
wangwu_num = int(input('请输入王五小麦入库量:'))
zhaoliu_num = int(input('请输入赵六麦子专营入库量:'))

stylex = lambda x: style_red if x > 10 else style

new_sheet.write(0, 0, tem_sheet.cell_value(0, 0), style_lishu22)
new_sheet.write(1, 0, tem_sheet.cell_value(1, 0), style_lishu18)
new_sheet.write(1, 1, tem_sheet.cell_value(1, 1), style_lishu18)
new_sheet.write(2, 0, tem_sheet.cell_value(2, 0), style_lishu18)
new_sheet.write(3, 0, tem_sheet.cell_value(3, 0), style_lishu18)
new_sheet.write(4, 0, tem_sheet.cell_value(4, 0), style_lishu18)
new_sheet.write(5, 0, tem_sheet.cell_value(5, 0), style_lishu18)

new_sheet.write(2, 1, zhangsan_num, stylex(zhangsan_num))
new_sheet.write(3, 1, lisi_num, stylex(lisi_num))
new_sheet.write(4, 1, wangwu_num, stylex(wangwu_num))
new_sheet.write(5, 1, zhaoliu_num, stylex(zhaoliu_num))

new_excel.save('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-2/PracticeAnswer/填写.xls')

1.3 fx1excel2excel.py

  • pip install pymysql
import xlrd
import xlwt
from xlutils.copy import copy

xlsx = xlrd.open_workbook('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-3/LessonCode/7月下旬入库表.xlsx')

table = xlsx.sheet_by_index(0)

all_data = []
for n in range(1, table.nrows):
    company = table.cell(n, 1).value
    price = table.cell(n, 3).value
    weight = table.cell(n, 4).value

    data = {'company': company, 'weight': weight, 'price': price}
    all_data.append(data)
# 以下内容可以用pandas的groupby轻易实现,这里不引入新知识,使用一个笨办法
a_weight = []
a_total_price = []
b_weight = []
b_total_price = []
c_weight = []
c_total_price = []
d_weight = []
d_total_price = []

for i in all_data:
    if i['company'] == '张三粮配':
        a_weight.append(i['weight'])
        a_total_price.append(i['weight'] * i['price'])
    if i['company'] == '李四粮食':
        b_weight.append(i['weight'])
        b_total_price.append(i['weight'] * i['price'])
    if i['company'] == '王五小麦':
        c_weight.append(i['weight'])
        c_total_price.append(i['weight'] * i['price'])
    if i['company'] == '赵六麦子专营':
        d_weight.append(i['weight'])
        d_total_price.append(i['weight'] * i['price'])


tem_excel = xlrd.open_workbook('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-3/LessonCode/统计表_模板.xls', formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()
font.name = '微软雅黑'
font.bold = True
font.height = 360
style.font = font

borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders

alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style.alignment = alignment

new_sheet.write(2, 1, len(a_weight), style)
new_sheet.write(2, 2, round(sum(a_weight), 2), style)
new_sheet.write(2, 3, round(sum(a_total_price), 2), style)
new_sheet.write(3, 1, len(b_weight), style)
new_sheet.write(3, 2, round(sum(b_weight), 2), style)
new_sheet.write(3, 3, round(sum(b_total_price), 2), style)
new_sheet.write(4, 1, len(c_weight), style)
new_sheet.write(4, 2, round(sum(c_weight), 2), style)
new_sheet.write(4, 3, round(sum(c_total_price), 2), style)
new_sheet.write(5, 1, len(d_weight), style)
new_sheet.write(5, 2, round(sum(d_weight), 2), style)
new_sheet.write(5, 3, round(sum(d_total_price), 2), style)


new_excel.save('E:/Project/Python_Project/CourseCode/Chapter1/S1-1-3/LessonCode/7月下旬统计表.xls')

1.3.3增删改查.py

import pymysql

database = pymysql.connect("127.0.0.1", "test", "test", "db", charset='utf8')
# 格式:pymysql.connect("MySQL服务器地址", "用户名", "密码", "数据库名", charset='utf8')
cursor = database.cursor()
# 初始化指针


# 增
# 格式:"INSERT INTO 表名 (字段1,字段2,字段3) VALUES (内容1,内容2,内容3);"

sql = "INSERT INTO data (date,company,province,price,weight) VALUES ('2019-9-20','河北粮食','河北','2200','45.1');"
cursor.execute(sql)
database.commit()  # 对存储的数据修改后,需要commit
database.close()

# 改
# 格式:"UPDATE 表名 SET 字段1=内容1,字段2=内容2  WHERE 条件;"

sql = "UPDATE data SET date='2018-09-21' WHERE DATE='2019-09-20';"
cursor.execute(sql)
database.commit()  # 对存储的数据修改后,需要commit
database.close()

# 查
# 基础语法:"SELECT 字段 FROM 表名 WHERE 条件"

sql = "SELECT company FROM data WHERE date='2018-07-21';"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
database.close()

# 删
# 格式:"DELETE FROM 表名 WHERE 条件;" 条件的写法 :字段=内容

sql = "DELETE FROM data WHERE date='2018-09-21';"
cursor.execute(sql)
database.commit()  # 对存储的数据修改后,需要commit
database.close()

1.3.3exercise.py

import pymysql
import xlrd
import datetime

database = pymysql.connect("127.0.0.1", "test", "test", "db", charset='utf8')
cursor = database.cursor()

sql1 = "DELETE FROM data ;"
cursor.execute(sql1)
database.commit()


def change_date(date_excel):
    first_date = datetime.date(1899, 12, 31).toordinal() - 1
    if isinstance(date_excel, float):
        date_excel = int(date_excel)
    date_mysql = datetime.date.fromordinal(first_date + date_excel)
    return date_mysql.strftime("%Y-%m-%d")


xlsx = xlrd.open_workbook('d:/7月下旬入库表.xlsx')
table = xlsx.sheet_by_index(0)
for i in range(1, table.nrows):
    sql2 = "INSERT INTO data (date,company,province,price,weight) VALUES ('%s','%s','%s','%s','%s');" % (
    change_date(table.cell_value(i, 0)), table.cell_value(i, 1), table.cell_value(i, 2), table.cell_value(i, 3),table.cell_value(i, 4))
    cursor.execute(sql2)
    database.commit()


sql3 ="SELECT SUM(weight) FROM data WHERE date>'2018-07-21' AND date<'2018-07-25' AND company='王五小麦' AND province='河北' "
cursor.execute(sql3)
print(cursor.fetchall()[0][0])

database.close()

1.3.4 fx2mysql2excel.py

import xlrd
import xlwt
from xlutils.copy import copy
import pymysql

database = pymysql.connect("127.0.0.1", "test", "test", "db", charset='utf8')

cursor = database.cursor()

sql = "SELECT company ,COUNT(company),SUM(weight),SUM(weight*price) FROM data  GROUP BY company"
cursor.execute(sql)
result = cursor.fetchall()
# print(result)
for i in result:
    if i[0] == '张三粮配':
        a_num = i[1]
        a_weight = i[2]
        a_total_price = i[3]
    elif i[0] == '李四粮食':
        b_num = i[1]
        b_weight = i[2]
        b_total_price = i[3]
    elif i[0] == '王五小麦':
        c_num = i[1]
        c_weight = i[2]
        c_total_price = i[3]
    elif i[0] == '赵六麦子专营':
        d_num = i[1]
        d_weight = i[2]
        d_total_price = i[3]

tem_excel = xlrd.open_workbook('E:/Project/Python_Project/CourseCode/Chapter1/S1-3-1/LessonCode/统计表_模板.xls', formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()
font.name = '微软雅黑'
font.bold = True
font.height = 360
style.font = font

borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders

alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style.alignment = alignment

new_sheet.write(2, 1, a_num, style)
new_sheet.write(2, 2, a_weight, style)
new_sheet.write(2, 3, a_total_price, style)
new_sheet.write(3, 1, b_num, style)
new_sheet.write(3, 2, b_weight, style)
new_sheet.write(3, 3, b_total_price, style)
new_sheet.write(4, 1, c_num, style)
new_sheet.write(4, 2, c_weight, style)
new_sheet.write(4, 3, c_total_price, style)
new_sheet.write(5, 1, d_num, style)
new_sheet.write(5, 2, d_weight, style)
new_sheet.write(5, 3, d_total_price, style)

new_excel.save('E:/Project/Python_Project/CourseCode/Chapter1/S1-3-1/LessonCode/7月下旬统计表.xls')

你可能感兴趣的:(#,4.2,Python,python,办公自动化)