脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python操作mysql、excel、pdf的示例

python操作mysql、excel、pdf的示例

2021-09-29 00:24JKYEC | Jake Python

这篇文章主要介绍了python操作mysql、excel、pdf的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下

一、学习如何定义一个对象

代码:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. # 1. 定义Person类
  5. class Person:
  6.  
  7. def __init__(self, name, age):
  8. self.name = name
  9. self.age = age
  10.  
  11. def watch_tv(self):
  12. print(f'{self.name} 看电视')
  13.  
  14. # 2. 定义loop函数
  15. # 打印 1-max 中的奇数
  16. def test_person():
  17. person = Person('Jake', 20)
  18. print(f'打印person的地址:', person)
  19. print(f'person.name:{person.name}')
  20. print(f'person.age:{person.age}')
  21. person.watch_tv()
  22.  
  23. person = Person('Koko', 18)
  24. print(f'打印person的地址:', person)
  25. print(f'person.name:{person.name}')
  26. print(f'person.age:{person.age}')
  27. person.watch_tv()
  28.  
  29. # 3. 执行calculate方法
  30. # 计算 当前值小于1,当前值:0
  31. # 计算 1 >= 1: True
  32. # 计算 2 >= 1: True
  33. # 计算 10 >= 1: True
  34. test_person()

执行结果:

python操作mysql、excel、pdf的示例

二、学习如何连接MySQL并查询

代码块:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. # pip3 install pymysql
  5.  
  6. import pymysql
  7.  
  8. from getpass import getpass
  9.  
  10. # from mysql.connector import connect, Error
  11. #
  12. host = 'xxxxxxx'
  13. port = 3306
  14. username = 'db_account_member'
  15. password = 'db_account_password'
  16. database = 'some_database'
  17.  
  18. def connect_db():
  19. return pymysql.connect(host=host,
  20. port=port,
  21. user=username,
  22. password=password,
  23. database=database,
  24. charset='utf8')
  25.  
  26. def print_error(e):
  27. print(f'错误类型:{type(e)}')
  28. print(f'错误内容:{e}')
  29.  
  30. def close_gracefully(cursor, conn):
  31. if cursor:
  32. cursor.close()
  33. if conn:
  34. conn.close()
  35.  
  36. # 查询数据库,可以写任意查询语句
  37. def query(sql):
  38. try:
  39. conn = connect_db() # 创建连接
  40. cursor = conn.cursor() # 建立游标
  41. cursor.execute(sql) # 执行sql语句
  42. return cursor.fetchall()
  43. except pymysql.Error as e:
  44. print_error(e)
  45. finally:
  46. close_gracefully(cursor, conn)
  47.  
  48. query_sql = 'select * from category where id = 1'
  49. rows = query(query_sql)
  50. print('category表中的数据如下:')
  51. print(rows)

执行结果:

python操作mysql、excel、pdf的示例

三、学习如何读写csv

代码:

  1. # -*- coding: UTF-8 -*-
  2.  
  3. # 1. 导入csv库
  4. import csv
  5.  
  6. file_name = '../resources/test.csv'
  7.  
  8. # 2. 定义headers和rows
  9. headers = ['index', 'name', 'sex', 'height', 'year']
  10.  
  11. rows = [
  12. [1, 'Jake', 'male', 177, 20],
  13. [2, 'Koko', 'female', 165, 18],
  14. [3, 'Mother', 'female', 163, 45],
  15. [4, 'Father', 'male', 172, 48]
  16. ]
  17.  
  18. # 3. 定义write_csv函数
  19. # 写入csv
  20. def write_csv():
  21. print(f'文件[{file_name}]准备写入')
  22. with open(f'{file_name}', 'w')as f:
  23. f_csv = csv.writer(f)
  24. f_csv.writerow(headers)
  25. f_csv.writerows(rows)
  26. print(f'文件[{file_name}]写入完毕')
  27.  
  28. # 读取csv
  29. def read_csv():
  30. print(f'文件[{file_name}]准备读取')
  31. with open(f'{file_name}')as f:
  32. f_csv = csv.reader(f)
  33. for row in f_csv:
  34. print(row)
  35. print(f'文件[{file_name}]读取完毕')
  36.  
  37. # 4. 执行write_csv函数
  38. write_csv()
  39. print('------')
  40. read_csv()

执行结果:

python操作mysql、excel、pdf的示例

四、读取xlsx

代码:

  1. # -*- coding: UTF-8 -*-
  2.  
  3. # 导引
  4. # 安装相关依赖
  5. # pip3 install xlrd
  6.  
  7. # 引入xlrd去支持读取xls相关的文件
  8. import xlrd
  9.  
  10. # 定义文件名
  11. file_name = '../resources/sku.xls'
  12.  
  13. # 1. 读取xls文件
  14. # 预计输出
  15. # sku.xls该文档有 3 个tab页
  16. sku_file = xlrd.open_workbook(file_name)
  17. print("{0}该文档有 {1} 个tab页".format(file_name, sku_file.nsheets))
  18. print("每个tab页,页名分别为: {0}".format(sku_file.sheet_names()))
  19.  
  20. # 2. 读取xls文件第1页
  21. # 预计输出
  22. # tab页名:Sheet1,该tab页共有59行,3列
  23. # A6方格的值:1908165140370878
  24. current_sheet_index = 0 # 下标0为第一页tab
  25. current_sheet = sku_file.sheet_by_index(current_sheet_index)
  26. print("tab页名:{0},该tab页共有{1}行,{2}列".format(current_sheet.name, current_sheet.nrows, current_sheet.ncols))
  27. print("A6方格的值:{0}".format(current_sheet.cell_value(rowx=5, colx=0)))
  28.  
  29. # 3. 打印每页的数据,每一行的数据为一个数组
  30. # 预计输出
  31. # [text:'1908154975415329', text:'鞋面是织物 鞋底是聚氨酯底的哦', text:'鞋底是5厘米 内增是3厘米 总高度是8厘米左右哦']
  32. # [text:'1908040228021948', text:'鞋面是飞织 鞋底是聚氨酯底的哦', text:'鞋底高度是3厘米左右哦']
  33. # ...以下省略后续打印
  34. for rx in range(current_sheet.nrows):
  35. print(current_sheet.row(rx))

执行结果:

python操作mysql、excel、pdf的示例

五、读写PDF

代码:

  1. import platform
  2. import pdfkit
  3.  
  4. # 这里根据自己的系统修改对应的wkhtmltopdf安装路径,修改其中一个就行了
  5. win_path = 'D:/tools/wkhtmltopdf'
  6. non_win_path = '/usr/local/bin/wkhtmltopdf'
  7.  
  8. def wkhtmltopdf_path():
  9. system = platform.system()
  10. if system == 'Darwin':
  11. print('苹果系统,可以生成pdf')
  12. path = non_win_path
  13. elif system == 'Windows':
  14. print('Windows系统,可以生成pdf')
  15. path = win_path
  16. elif system == 'Linux系统':
  17. print('Linux系统,可以生成pdf')
  18. path = non_win_path
  19. else:
  20. print('其他系统,暂不支持生成pdf')
  21. raise Exception('其他系统,暂不支持生成pdf')
  22. return path
  23.  
  24. def pre_config():
  25. return pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path())
  26.  
  27. # 从链接地址生成pdf
  28. def generate_pdf_from_url(url, output_file_path):
  29. config = pre_config()
  30. pdfkit.from_url(url, output_file_path)
  31.  
  32. # 从字符串生成pdf
  33. def generate_pdf_from_string(str, output_file_path):
  34. config = pre_config()
  35. pdfkit.from_string(str, output_file_path)
  36.  
  37. generate_pdf_from_url('https://baidu.com', '../temp/baidu_test.pdf')
  38.  
  39. generate_pdf_from_string('hello', '../temp/hello.pdf')

wkhtmltopdf这个东西一定要装,不然无法生成pdf,会报IO方面的错误,小白照做就可以,不需要理解

执行结果

python操作mysql、excel、pdf的示例

生成的文件长这个样子

python操作mysql、excel、pdf的示例

baidu_test.pdf

python操作mysql、excel、pdf的示例

hello.pdf

python操作mysql、excel、pdf的示例

以上就是python操作mysql、excel、pdf的示例的详细内容,更多关于python操作mysql、excel、pdf的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/6943103839532744712

延伸 · 阅读

精彩推荐