网站制作学习网Python→正文:python读写excel
字体:

python读写excel

Python 2023/7/20 14:36:17  点击:不统计


 python读写excel,直接看下面代码,复制后可以直接保存到本地.py文件直接运行。

# coding = utf-8
"""
@ author:
@ info: python 读写excel
"""
import os
from openpyxl import Workbook,load_workbook # 安装扩展 pip install openpyxl
from openpyxl.styles import Border, Side


class Main:
def __init__(self):
self.excel_path = os.getcwd()

def run(self):
data = [['title-date', 'title-num'],
['2023-07-01', '1 www'],
['2023-07-01', '2 forasp'],
['2023-07-01', '3 cn'],
]
file_name = "test.xlsx"
self.write_excel_file(data, file_name)
read_data = self.read_excel_file(file_name)
print(read_data)
pass

# 读取 csv
def read_excel_file(self, file_name, sheet_name = "test"):
result = []
print("开始处理:", self.excel_path + "/" + file_name)
excel_file_obj = load_workbook(self.excel_path + "/" + file_name)
# excel_file_obj.get_sheet_names() 返回所有 sheet 名称
sheet_obj = excel_file_obj[sheet_name]
# 获取最大行
data = list(sheet_obj.iter_rows(values_only=True))
#sheet_title = data[0] # 获取表头
sheet_datas = data[0:] # 获取从0-末尾表数据
for row in sheet_datas:
result.append(row)
excel_file_obj.close()
return result

# 写csv文件
def write_excel_file(self, data, file_name, sheet_name = "test"):
excel_file_obj = Workbook()
sheet = excel_file_obj.active
sheet.title = sheet_name
sheet_obj = excel_file_obj[sheet_name]
# sheet_obj.column_dimensions['B'].width = 20 # 设置列宽,如果需要 B表示第 B 列
# sheet_obj.row_dimensions[1].height = 25 # 设置行高 1 表示第一行
line_num = 1 # 定义写入的起始行号
for row in data:
for index, item in enumerate(row):
cell = sheet_obj.cell(line_num, index + 1, item) # 循环为每个单元格写内容
cell.border = self.set_border() # 设置单元格 边框,如果需要
# cell.alignment = Alignment(wrapText=True,horizontal='center',vertical='center')
# 设置单元格 对齐方式, 如果需要。 wrapText表示换行 horizontal 水平对齐方式 vertical垂直对齐方式
line_num = line_num + 1
excel_file_obj.save(self.excel_path + "/" + file_name)
pass

# 设置边框信息
def set_border(self, t_color='000000', b_color='000000', l_color='000000', r_color='000000'):
border = Border(top=Side(border_style=Border.top, color=t_color),
bottom=Side(border_style=Border.bottom, color=b_color),
left=Side(border_style=Border.left, color=l_color),
right=Side(border_style=Border.right, color=r_color))
return border


if __name__ == "__main__":
obj = Main()
obj.run()

原文章%77w%77%2Ef%6F%72%61%73%70%2E%63n

·上一篇:python读写csv >>    ·下一篇:python 函数名后面的箭头 >>
推荐文章
最新文章