python 写入excel_实用小工具python数组快速写入excel表格
生活随笔
收集整理的這篇文章主要介紹了
python 写入excel_实用小工具python数组快速写入excel表格
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在進行數(shù)值計算時有時會產(chǎn)生大量的數(shù)據(jù),有時候需要與其他軟件計算的數(shù)據(jù)進行對比,這時候?qū)?shù)據(jù)輸出excel表格就很重要了。
借助openpyxl可以方便地輸出相應(yīng)的數(shù)據(jù),精簡版如下:
from openpyxl import load_workbook,Workbookfrom openpyxl.styles import Alignment,PatternFillimport timeclass Excel(object): def __init__(self): self.timestr = time.strftime("%Y-%m-%d-%H-%M") self.STYLE_alig_center = Alignment(horizontal='center') self.STYLE_fillstyle_1 = PatternFill(fill_type='solid',fgColor='99ccff') def new(self,filename): assert("." in filename) self.filename = filename self.wb = Workbook()????????self.sheet?=??self.wb.active def get_cell(self,row,col):????????return?self.sheet.cell(row,col)???????? def set_alignment(self,cellobj,style):????????cellobj.alignment?=?style???????? def set_fillstyle(self,cellobj,style):????????cellobj.fill?=?style???????? def write_header(self,row_id,header_list): for i,hi in enumerate(header_list): cell = self.get_cell(row_id,i+1) cell.value = hi self.set_alignment(cell,self.STYLE_alig_center)????????????self.set_fillstyle(cell,self.STYLE_fillstyle_1)???????????? def write_Array(self,Arr,start_row_id,col_id): for i,arri in enumerate(Arr): cell = self.get_cell(start_row_id+i,col_id) try: cell.value = arri except:????????????????cell.value?=?str(arri) def close(self): self.wb.save(self.filename) def close_with_time(self): contents = self.filename.split(".") new_name = contents[0]+"-"+ self.timestr +'.'+contents[1] self.wb.save(new_name)使用方法如下:
if __name__ == "__main__": import numpy as np excel = Excel() excel.new("test.xlsx") xs = np.linspace(0,1) ys = np.ones_like(xs) xy = np.stack([xs,ys]).T excel.write_header(1,["點坐標(biāo)","a方法計算結(jié)果","b方法計算結(jié)果"])????excel.write_Array(xy,2,1)? excel.write_Array(xs,2,2) # 寫入數(shù)據(jù) excel.write_Array(ys,2,3) # excel.close_with_time() excel.close()總結(jié)
以上是生活随笔為你收集整理的python 写入excel_实用小工具python数组快速写入excel表格的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: union和union all有什么区别
- 下一篇: python expect模块_PYTH