python--CSV和Excel封装

import csv

def write_csv(filePath,data):
    with open(filePath,mode="w",newline="",encoding="utf-8") as csvfile:
        writer=csv.writer(csvfile);
        for line in data:
            writer.writerow(line);


def read_csv(filePath):
    data=[];
    with open(filePath,mode="r",encoding="utf-8") as csvfile:
        reader=csv.reader(csvfile);
        for line in reader:
            data.append(line)


    return data;
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet

def write_excel(filepath,sheetName,header,data):
    wb=Workbook();
    ws=wb.create_sheet(sheetName);
    #写入header
    ws.append(header)
    row=1
    for lineData in data:
        row=row+1;
        col=1
        for value in lineData.values():
            ws.cell(row=row,column=col,value=value)
            col=col+1;
    wb.save(filepath)

def read_excel(filePath,sheetName):
    wb=load_workbook(filePath)
    ws:Worksheet=wb[sheetName]
    data=[];
    for x in range(2,ws.max_row+1):
        dic={}
        for y in range(1,ws.max_column+1):
            dic[ws.cell(1,y).value]=ws.cell(row=x,column=y).value
        data.append(dic)

    return data;

调用:


from ToolUtils.csv_handler import read_csv,write_csv
import os

filePath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"data\\test.csv")


testdata=(["编号","标题"],["1","登录成功1"],["2","登录成功2"],["3","登录成功3"])

write_csv(filePath,testdata)

readData=read_csv(filePath)
for line in readData:
    print(line)

from ToolUtils.excel_handler import write_excel,read_excel

filePath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"data\data.xlsx")
header=["title","method","url"]
testData=[{"tile":"用户注册1","method":"get","url":"http://www.baidu"},{"title":"用户注册2","method":"post","url":"http//www.badu.com"},
          {"title":"用户注册3","method":"post","url":"http://www.baidu.com"}]

write_excel(filePath,"MySheet",header,testData)

print(read_excel(filePath,"MySheet"))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值