1. 程式人生 > >Python處理Excel(一):Excel的簡單處理

Python處理Excel(一):Excel的簡單處理

       來公司的第一個任務,就是用Python寫一個自動處理excel的指令碼,需要實現的功能為:1.讀取外部的引數 2.從一個excel表格中讀取公式和文字資訊 3.將1中的引數帶入到2中的公式中計算出結果並寫入一個新建的excel表格中。

       於是我的Python學習之路就此拉開序幕,學習之路需要腳踏實地,一步一個腳印,勉勵自己能夠堅持的記錄下去~

專案的原始碼如下

#! /usr/bin/env python
# -*- coding:utf-8 –*-
 
import xlrd
import xlwt
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8') 

def format_xlsx():
	font0 = xlwt.Font()
	font0.name = 'Times New Roman'
	font0.colour_index = 2
	font0.height=225
	font0.bold = True
	alignment = xlwt.Alignment()
	alignment.horz = xlwt.Alignment.HORZ_CENTER
	pattern = xlwt.Pattern()
	pattern.pattern = xlwt.Pattern.SOLID_PATTERN
	pattern.pattern_fore_colour = 5
	style = xlwt.XFStyle()
	style.font=font0
	style.alignment = alignment
	style.pattern = pattern
	return style


def open_xlsx(file='f.xlsx'):
	data=xlrd.open_workbook(file)
	return data

def cal_xlsx(file='f.xlsx',sheet_index=0,width=1,height=1,frames=1,style=1,save_file='result.xlsx'):	
	data=open_xlsx(file)
	table=data.sheets()[sheet_index]
	#---------------------
	file_w=xlwt.Workbook()
	table_w=file_w.add_sheet(data.sheet_names()[sheet_index],cell_overwrite_ok=True)
	#--------------------
	tab_row=table.nrows
	tab_col=table.ncols
	rowv=table.row_values(0)
	colv=table.col_values(0)
  
	for x in range(1,tab_col):
		table_w.write_merge(0,0,(x*2-1),x*2,rowv[x],style)
		table_w.col(x*2-1).width = 8000  
	for y in range(0,tab_row):
		table_w.write(y,0,colv[y],style)

	for row in range(1,table.nrows):
		for col in range(1,table.ncols):  
			
			formula0=table.cell(row,col).value
			table_w.write(row,col*2-1,formula0.replace('width',str(width)).replace('height',str(height)).replace('frames',str(frames)))
	for row in range(1,table.nrows):
		for col in range(1,table.ncols):
			formula0=table.cell(row,col).value
			table_w.write(row,col*2,eval(formula0))
	file_w.save(save_file)
	return  0



def main():
	print "1.請輸入需要載入的引數值>>>"
	while(1):
		try:
			width=input("請輸入width的值:")
		except Exception,e:
			print '輸入的資料不合法,請輸入【整數】或者【浮點數】!',e
		else:
			break
	while(1):
		try:
			height=input("請輸入height的值:")
		except Exception,e:
			print '輸入的資料不合法,請輸入【整數】或者【浮點數】!',e
		else:
			break
	while(1):
		try:
			frames=input("請輸入frames的值:")
		except Exception,e:
			print '輸入的資料不合法,請輸入【整數】或者【浮點數】!',e
		else:
			break
	
	print "2.請輸入需要載入公式的文件路徑名>>>"
	
	while(1):
		try:
			path=raw_input("請輸入EXCL路徑名稱:")
		except Exception,e:
			print '輸入的資料不合法,請輸入完整的路徑名稱!',e
		else:
			break
	
	
	print "3.請輸入需要處理的表單序號>>>"
	while(1):
		try:
			index=input("請輸入EXCL表單序號:")
		except Exception,e:
			print '輸入的資料不合法,請輸入【整數】!',e
		else:
			break

	print "4.請輸入生成EXCL的名稱[xxx.xlsx]>>>"
	while(1):
		try:
			savefile=raw_input("請輸入儲存處理結果的EXCL名稱:")
		except Exception,e:
			print '輸入的資料不合法!',e
		else:
			break
	style=format_xlsx()
	try:
		cal_xlsx(path,index,width,height,frames,style,savefile)
	except Exception,e:
		print '處理失敗!',e
	else:	
		print '表格生成成功,請查詢結果!'
		
main()	
	

下面說明在編寫這個程式時遇到的問題和解決的方法:

1.

#! /usr/bin/env python

        必須置於檔案的第一行,用於告訴作業系統使用哪種程式去執行檔案中的程式碼,並指出解釋程式的位置,如果使用 ./xxx.py 的方法執行指令碼檔案那麼這行程式碼是必不可少的,如果執行時使用 python xxx.py 的方法顯式的指出是使用Python直譯器執行檔案程式碼,則可以不需要這行程式碼。

2.

# -*- coding:utf-8 –*-
或者
#coding=utf-8

        必須在檔案的第一行或者第二行指定該編碼宣告(包括空行)。Python預設的指令碼檔案都是使用ASCII編碼的,當檔案中出現了漢字等非ASCII編碼範圍的字元時,就需要該條程式碼來修正。該行程式碼可以把預設的指令碼編碼方式修改為UTF-8,這是一種支援漢字的編碼方式。既然提到了編碼,那麼這裡就展開說明一下。

ASCII編碼

        一個位元組8位,可以表示256種不同的狀態,也就可以代表256種字元。上個世紀60年代,美國製定了這套字元編碼,對英語字元與二進位制位之間的關係,做了統一規定。這被稱為ASCII碼,一直沿用至今。ASCII碼一共規定了128個字元的編碼,使用了後7位,第8位統一規定為0。

非ASCII編碼

        漢字等非英文字母組合表示的字元,使用ASCII編碼就不能表示,於是便需要其他的編碼方式,比如漢字可以使用GB2312編碼,使用兩個位元組表示一個漢字。理論上可以表示65536個漢字元號。如果使用不同的編碼編碼和解碼檔案就會出現亂碼,所以就需要一個統一的編碼出現,這就是Unicode

。UTF-8就是一種Unicode的實現方式之一,其使用1-4個位元組表示一個符號,根據不同的符號變化位元組的長度。

#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8') 

       這行雖然註釋了,但是還是應該記錄一下。指令碼檔案預設的解碼方式為ASCII。使用UTF-8編碼而使用ASCII解碼就會出現錯誤,為了實現編碼和解碼的統一,我們就需要改變預設的編碼方式。

codes:這個模組定了標準Python解碼器(編碼器和解碼器)的基類,並提供了內部Python編碼器登錄檔的入口,該登錄檔管理編碼器和錯誤處理查詢程序。

codecs.encode(obj[,encoding[,errors]]

codecs.decode(obj[,encoding[,errors]])

兩個物件均使用編碼器註冊編碼,預設的編碼是ascii

3.

def format_xlsx():
	font0 = xlwt.Font()
	font0.name = 'Times New Roman'
	font0.colour_index = 2
	font0.height=225
	font0.bold = True
	alignment = xlwt.Alignment()
	alignment.horz = xlwt.Alignment.HORZ_CENTER
	pattern = xlwt.Pattern()
	pattern.pattern = xlwt.Pattern.SOLID_PATTERN
	pattern.pattern_fore_colour = 5
	style = xlwt.XFStyle()
	style.font=font0
	style.alignment = alignment
	style.pattern = pattern
	return style

        設定excel的格式。拿字型舉例,首先例項化一個字型類,然後設定它的name,colour,height,width,bold等屬性,例項化一個style類,將填充好的字型類賦值給style中的font屬性中。XFStyle類包含如下表所示的幾種屬性。

Group Attributes
Number format Number format index (index to FORMAT record)
Font Font index (index to FONT record)
Alignment Horizontal and vertical alignment, text wrap, indentation,orientation/rotation, text direction
Border Border line styles and colours
Background Background area style and colours
Protection Cell locked, formula hidden
style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;'
                              'font: colour white, bold True;')

     使用easyxf()函式可以更快的建立一個style。

4.

cal_xlsx(file='f.xlsx',sheet_index=0,width=1,height=1,frames=1,style=1,save_file='result.xlsx'):
       這裡需要注意的時變數的順序問題,有預設值的引數必須放到沒有預設值的引數之前,def func(y=2, x):這種函式是不被允許的,執行會報錯。

5.

file_w=xlwt.Workbook()
table_w=file_w.add_sheet(data.sheet_names()[sheet_index],cell_overwrite_ok=True)
classxlwt.Workbook.Workbook(encoding='ascii',style_compression=0)
       建立的Excle表格預設的編碼為ASCII,如果需要寫入漢字,需要傳入變數encoding='utf-8'。如果需要向一個單元格寫入的次數不止一次,那麼傳入引數cell_overwrite=true


6.

table_w.write(row,col*2,eval(formula0))
       eval() 函式可以計算傳入其中的表示式的值。