Friday, December 19, 2008

用python控制excel,请沈高手指点些比较简单的操作方法(**)


用python控制excel,请沈高手指点些比较简单的操作方法(**)

主要用了pyExcelerator模块,下载地址:http://sourceforge.net/projects/pyexcelerator


下面是代码,主要功能是将excel中读取的内容重新排版;


#!c:\python24\python.exe
#coding=cp936
from pyExcelerator import *
import tkFileDialog
class App2:
    def __init__(self,x,z,a):
        self.x=x
        self.z=z
        self.a=a
        self.sheets=sheets=parse_xls(self.a)  #读取excel文件并以字典的形式存储在sheets下
        self.w=w=Workbook()                   #新建一个excel文件
        self.ws=ws=w.add_sheet('firstexcel')  #excel文件内新建一个表
        self.cp1=cp1=[self.sheets[0][1][(5, 0)]] 
    def excel_py_v(self):
        self.ws.write(0, 5, self.sheets[0][1][(0, 0)])  #标题
        self.cp1=[self.sheets[0][1][(5, 0)]]
        self.ws.write(2, 1, self.cp1[0])  #产品
        self.ws.write(1,12,'max_input_all')
        self.ws.write(29,12,'cost_all')
        for self.x in range(500):
            self.x = self.x+1
            if self.sheets[0][1].has_key((int(5+self.x),0)):
                if self.sheets[0][1][(int(5+self.x),0)] == self.cp1[0]:
                    self.z=self.z+1
                    self.y = self.z
                for self.yy in range(int(self.y/2+1)):
                    self.ws.write(int(self.yy+3),0,self.sheets[0][1][(int(5+(2*self.yy)),1)]) # 时间
          
                if self.sheets[0][1][(int(5+self.x),0)] in self.cp1 and self.x > 0:
                    for self.yy in range(int(self.y/2+1)):
                        self.ws.write(int(self.yy+3),1,self.sheets[0][1][(int(5+(2*self.yy)),2)]) # 总呼入数量
               
                        self.ws.write(int(self.yy+3+28)-1,1,self.sheets[0][1][(int(5+(2*self.yy)),4)]) # 总应答数量
   
                if self.sheets[0][1][(int(5+self.x),0)] not in self.cp1:
                    self.cp1.append (self.sheets[0][1][(int(5+self.x),0)])
                    self.ws.write(2,len(self.cp1),self.cp1[-1])
                    for self.yy in range(int(self.y/2+1)):
                        self.ws.write(int(self.yy+3),len(self.cp1),self.sheets[0][1][(int(self.x+5+(2*self.yy)),2)]) # 总呼入数量
                       
self.ws.write(int(self.yy+3+28)-1,len(self.cp1),self.sheets[0][1][(int(self.x+5+(2*self.yy)),4)])
# 总应答数量                       
            else:
                break
        self.w.save('save_index.xls')


if __name__=='__main__':
    App2(0,0,tkFileDialog.askopenfilename()).excel_py_v()


感觉比较麻烦的是读取,用pyExcelerator读取excel的内容,将会以字典的形式存储,所以导入并排版的话较复杂...汗一个``  请沈高手指点些比较简单的操作方法```








No comments: