python3读取xlsx文件内容
相关模块:
- openpyxl
- xlsxwriter
- xlrd只读取xls文件中的内容
openpyxl:
(部分内容来自官网http://openpyxl.readthedocs.io/en/stable/usage.html)
阅读现有的工作薄:
from openpyxl import load_workbook
wb = load_workbook(filename="文件名")
sheet_ranges = wb["sheet名"]
print(sheet_ranges['D18'].value) # 将index为D18的值读取出来
xlwt例子:
import xlwt, os, sys, glob, time, datetime
# define parameter
filepath = 'infomations.txt'
xlsname = '20230410.xls'
# class instance
workbook = xlwt.Workbook(encoding='ascii')
worksheet = workbook.add_sheet('第一个page')
style = xlwt.XFStyle() # 初始化样式
# define style
font = xlwt.Font() # 创建字体
font.name = '微软雅黑'
font.bold = True # 黑体
font.underline = False # 下划线
font.italic = True # 斜体
style.font = font # 设定字体
# 设置对齐方式
alignment = xlwt.Alignment() # 创建对齐方式
alignment.horz = 0x02
alignment.vert = 0x01
alignment.wrap = 0x01
style.alignment = alignment
xlswriter例子:
import xlsxwriter
"""
只能写入xlsx文件内容,不能读取
每次都是一个全新的sheet
"""
xlsname = 'hello.xlsx'
workbook = xlsxwriter.Workbook(xlsname)
worksheet1 = workbook.add_worksheet('第一个sheet页')
bold = workbook.add_format({'bold': True})
worksheet1.write(0,1, 'hello world', bold)
worksheet2 = workbook.add_worksheet('第二个sheet页')
worksheet2.write(0,1, 'hello world', bold)
workbook.close()
xlrd例子:
import xlrd
# xlrd仅支持xls格式的excel文档读取,这个读取比较简单,不做详细的笔记
xlsname = '20230410.xls'
xlsname2 = 'V20230407-01.xlsx'
exec = xlrd.open_workbook(xlsname)
sheet1 = exec.sheet_by_index(0)
num_rows = sheet1.cell(1,0).value
print(num_rows)