python處理xlsx多sheet文件

需求:每個xlsx共有20個sheet,每個sheet兩列。對第一列每個值加0.924,第二列每個值除以0.19625。對處理後的結果,以第一列爲x,第二列爲y,生成一條曲線,求與指定直線的交點。其中sheet1-10的指定直線爲x=0.225, sheet11-20的指定直線爲0.75.

import xlrd  
import shapely.geometry as SG 
import xlwt
import numpy as np
import os

file_path="/Users/chenhonghu/Desktop/pre"
new_path="/Users/chenhonghu/Desktop/res"
file_list=os.listdir(file_path)
for file in file_list:
    workbook=xlrd.open_workbook(os.path.join(file_path, file))
#         workbook=xlrd.open_workbook("/Users/chenhonghu/Downloads/N-146-2.xlsx")  #文件路徑
    book=xlwt.Workbook(encoding="utf-8",style_compression=0)
    sheet2=book.add_sheet("result",cell_overwrite_ok=True)
    cor_res1=[]#存放0.225組
    cor_res2=[]#存放0.27組
    print(file)
    names=workbook.sheet_names()#讀每個sheet
    count=0
    for i in range(1, len(names)):
        if i==1:
            cor_res1.append("0.225組:")
            print("0.225組:")
        if count==20:
            count=20+1
        worksheet=workbook.sheet_by_index(i)
        col_data1=worksheet.col_values(0)  #獲取第一列的內容
        row1=[]
        for row1_num in col_data1:
            if type(row1_num)==float:
                row1.append(row1_num+0.924)#第一列每個值加0.924

        for j in range(0, len(row1)):
            sheet2.write(j, count, row1[j])#第一列寫入sheet

        col_data2=worksheet.col_values(1)
        row2=[]
        for row2_num in col_data2:
            if type(row2_num)==float:
                row2.append(row2_num/0.19625)#第二列每個值除以0.19625

        for j in range(0, len(row2)):
            sheet2.write(j, count+1, row2[j])

        count=count+2#每張sheet列數加2

        line=SG.LineString(list(zip(row1, row2)))#獲得第一列和第二列的曲線

        xline=SG.LineString([(0.27, -2), (0.27, 2)])#x=0.27的直線
        yline=SG.LineString([(0.225,-2), (0.225, 2)])
        if i==11:
            cor_res2.append("0.27組:")
            print("0.27組:")
        if i<=10:
            coords=np.array(line.intersection(yline))#求交點
            print(max(coords[0][1], coords[1][1]))#求交點的最大值
            cor_res1.append(max(coords[0][1], coords[1][1]))
        else:
            coords=np.array(line.intersection(xline))
            print(max(coords[0][1], coords[1][1]))
            cor_res2.append(max(coords[0][1], coords[1][1]))
                           
    for k in range(0, len(cor_res1)):
        sheet2.write(k, 44, cor_res1[k])#交點寫入表
    for k in range(0, len(cor_res2)):
        sheet2.write(k, 45, cor_res2[k])
    book.save(os.path.join(new_path, os.path.splitext(file)[0]+".xls"))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章