Python文件处理excel

一:关于Excel

1.创建excel

from xlwt import *

file = Workbook(encoding='utf-8')
table = file.add_sheet(u"kwss")
file.save("E:\sduty\kwss.xls")

2.读取excel

from xlwt import *
myWorkbook = open_workbook(r'E:\siteVerify\text\data\bowen_20180529171858.xls')
mySheets = myWorkbook.sheet_by_name(u'sheet1')
nrows = mySheets.nrows
for i in range(0,nrows):
    title = mySheets.cell_value(i,0) #取得表中的数据

3.写入excel

#encoding=utf-8
from xlwt import *
from xlrd import *
import random
import os


myexcel = Workbook(encoding='utf-8')
table = myexcel.add_sheet(u"sheet")
fileDir=r'E:\siteVerify\demo\framework'
L = []
for root,dir,files in os.walk(fileDir):  #遍历整个文件夹目录,将文件夹文件,写入excel
    for file in files:
            # if os.path.splitext(file)[1] == '.json':
        L.append(os.path.join(root,file))
for i,j in enumerate(L):
    table.write(i,0,i)
    table.write(i,1,j)

myexcel.save("E:\siteVerify\sduty\kwss.xls")
 
  

4.读取excel写入同一个excel

import requests
import xlrd
import xlwt
from xlutils.copy import copy


myWorkbook = xlrd.open_workbook(r'E:\siteVerify\text\data\1.xls')
#获取Excel工作表
mySheets = myWorkbook.sheet_by_name(u'sheet1')
#获取行数、列数
nrows = mySheets.nrows
#ncols = mySheets.ncols
#复制一份表格
wb = copy(myWorkbook)
ws = wb.get_sheet('sheet1')
#接口地址
url = "http://*.*.*.*:8000/predict"
#读取表格每一行数据的前两列,之后将接口的响应写入第三列
for i in range(0,nrows):
      #获取表格中的title
      title = mySheets.cell_value(i,0)
      #获取表格中的content
      content = mySheets.cell_value(i,1)
      #带入函数,得到响应值
      body = {"content": content, "title": title}
      response = requests.post(url, data=body)
      print response.text
      #循环写入第三列
      ws.write(i,2,response.text)
      #保持表格
      wb.save(r'E:\siteVerify\text\data\1.xls')


你可能感兴趣的:(语言-python)