Pythonファイル処理excel

8320 ワード

一: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')