openpyxl读写

import time,os
from openpyxl import load_workbook
from openpyxl import Workbook


def create_excel():
    #新建并写入数据
    data=['单号','aa','bb']
    wb = Workbook()
    sheet = wb.active
    for i in range(len(data)):
        sheet["A%d" % (i+1)].value = data[i]
#     wb.save(filename = r"d:\empty_book1.xlsx" )
    ti = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
    name='saved_{0}.xlsx'.format(ti)
    f_path=get_path()
    new_path=os.path.join(f_path,name)
    wb.save(filename = new_path )
    return new_path

def get_path(self):
    f_path=os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    path=os.path.join(f_path.encode('utf-8'),'temp')
    return path
 
if __name__ == '__main__':
    print create_excel()
xlwt、wlrd只能读写xls文件,而不能操作xlsx文件。openpyxl只能操作xlsx文件而不能操作xls文件。
1、基本概念
在openpyxl中,主要用到三个概念:Workbooks,Sheets,Cells。Workbook就是一个excel工作表;Sheet是工作表中的一张表页;Cell就是简单的一个格。openpyxl就是围绕着这三个概念进行的,不管读写都是“三板斧”:打开Workbook,定位Sheet,操作Cell。

 

具体参考:

http://www.cnblogs.com/anpengapple/p/6399304.html?utm_source=itdadao&utm_medium=referral
http://blog.csdn.net/dkleaves/article/details/45506451

二、xlrd

xlrd写入:

def write_to_excel(self,excel_path,data): 
        '''向Excel中写入数据
        Arguments:
            excel_path:excel模板的路径
            data:需要向Excel写入的数据
        Returns:
            str:返回新生成的Excel的路径
        Raises:
            Exception:None
        Examples:
            data:{"1":[]}
        '''
        try:
            sheet=xlrd.open_workbook(excel_path)
            rb=copy(sheet)
            ws=rb.get_sheet(0)
            ldata=[]
            num = [a for a in data]             
            #for循环指定取出key值存入num中
            num.sort()   
            for x in num:                       
            #for循环将data字典中的键和值分批的保存在ldata中
                t=[]
                for a in data[x]:
                    t.append(a)
                ldata.append(t)
            for i,p in enumerate(ldata):
                for j,q in enumerate(p):
                    ws.write(i+1,j,q)
            #将新的Excel文件另存,文件名以excel_save+当前时间命名
            ti = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))#u获取当前时间
            name='excel_save{0}.xls'.format(ti)
            f_path=self.get_path()
            save_path=os.path.join(f_path,name)
            rb.save(save_path)  
            return save_path
        except:
            raise BenefitError(u'向Excel写入数据失败')

读取文件

 

def read_excel(self,file_path,colname_index=0,sheet_index=0):
        '''读取Excel数据
        Arguments:
            file_path:excel文件的路径
            colname_index:表头列名所在的行
            sheet_index:表的索引
        Returns:
            None
        Raises:
            Exception:None
        Examples:
            None
        '''
        try:
            data=xlrd.open_workbook(file_path)
            table=data.sheets()[sheet_index] 
            nrows=table.nrows
            colname=table.row_values(colname_index)
            data_list=[]
            for rownum in range(1,nrows):#u读取每一行的数据
                row=table.row_values(rownum)
                if row:
                    ldata={}#u将列名和每一列的数据以字典的
                    for i  in range(len(colname)):
                        a=row[i]
                        b=colname[i]
                        ldata[b]=a
                data_list.append(ldata)
            return data_list 
        except:
            raise BenefitError(u'读取Excel数据失败')

 三,读取xml

def read_xml(self,file_path):    
        '''读取xml数据
         Arguments:
            file_path:xml文件的路径
        Returns:
            list:所有数据
        Raises:
            Exception:None
        Examples:
            None
        
        '''
        col=[]
        row=[]
        data=[]
        try:
            doc=xml.dom.minidom.parse(file_path)
            root=doc.documentElement
            dom=root.getElementsByTagName('Row')
            cel=dom[0].getElementsByTagName('Cell')
            for childnode in cel:#获取第一行数据,作为字典的键
                m_data=childnode.getElementsByTagName('Data')
                if m_data[0].firstChild:
                    col.append(m_data[0].firstChild.data)
                    
                else:
                    col.append('')
            for i in range(1,len(dom)):#获取2到n行数据,作为字典的值
                cel1=dom[i].getElementsByTagName('Cell')
                for childnode in cel1:
                    l_data=childnode.getElementsByTagName('Data')
                    if l_data[0].firstChild:
                        row.append(l_data[0].firstChild.data)
                    else:
                        row.append('')
                dic=dict(zip(col,row))#合并表头和表中的数据,组成字典
                data.append(dic)#将每一个字典的数据存储到列表中
            return data   
        except:
            raise BenefitError(u'读取xml数据失败')

四,解压文件

 

def unzip(self,name):
        '''解压文件
        Arguments:
            zip_path:压缩文件的路径
            extract_path:解压文件的路径
            name:Excel模板的名称
        Returns:
            str:返回所需要的Excel的文件路径
        Raises:
            Exception:BenefitError
        Examples:
            None
        '''
        sleep(1)
        zip_path=self.get_path()#u获取下载文件的默认路径
        extract_path=self.get_path()#u解压路径设为默认路径
        file_list=os.listdir(zip_path)
        for  file_name in file_list:
            if os.path.splitext(file_name)[1]=='.zip':
                file_zip=zipfile.ZipFile(os.path.join(zip_path,file_name),'r')
                for f in file_zip.namelist():
                    file_zip.extract(f, extract_path)
                    if name in f.decode('utf-8'):
                        break 
                file_zip.close()
                os.remove(os.path.join(zip_path,file_name))
                path=os.path.join(extract_path,f)
                return path.format('u')
                break
        else:
            raise BenefitError(u'未找到压缩文件')

 

  

 

  

 

posted @ 2017-05-31 17:27  Mytesting  Views(530)  Comments(0Edit  收藏  举报