python excel讀寫數據


python 讀取excel內容,包含表格日期處理

 

# -*- coding: utf-8 -*-
import  xlrd
#讀取excel表格
workbook=xlrd.open_workbook(r'D:\demo.xlsx')#打開excel文件
table = workbook.sheet_by_name('Sheet2')#將文件內容表格化
rows_num = table.nrows # 獲取行
cols_num = table.ncols # 獲取列

res=[]#定義一個數組
for rows in range(rows_num):
    for cols in range(cols_num):
        cell_value=table.cell(rows,cols).value#獲取excel中單元格的內容
        ctype=table.cell(rows,cols).ctype#獲取單元格內容的數據類型:ctype:1整型 2浮點型 3日期 4布爾
        if cell_value=='':#判斷如果單元格內容為空
            cell_value='--'#設置顯示內容為--
            res.append(cell_value)#將內容加入到res數組
        elif ctype ==3:#判斷單元格內容為日期類型
                cell_value=xlrd.xldate_as_datetime(cell_value,0)#將內容轉為datetime格式
                cell_value=cell_value.strftime(("%Y/%m/%d"))#格式轉換顯示
                res.append(cell_value)
        elif isinstance(cell_value,unicode):#轉碼
                cell_value=cell_value.encode('utf-8')
                res.append(cell_value)
        elif isinstance(cell_value,float):#轉碼
                cell_value = str(cell_value)
                cell_value = cell_value.decode('utf-8').encode('gb2312')
                res.append(cell_value)
    res.append('|')
res = ','.join(res)
res = res.split('|')

for i in range(len(res)-1):
    print '',i+1,'行數據:',res[i].strip(',')

讀取內容整數變為小數,有2個解決辦法:

1、在excel中數字簽名加個英文單引號: '

2、通過程序代碼判斷單元格內容的ctype來解決

if ctype == 2 and cell % 1 == 0.0: # ctype為2且為浮點
cell = int(cell) # 浮點轉成整型
cell = str(cell) # 轉成整型后再轉成字符串,如果想要整型就去掉該行

python寫入內容

# -*- coding: utf-8 -*-
import xlsxwriter
import time
#excel表格寫數據

startime=time.time()#獲取文件創建時間

workbook=xlsxwriter.Workbook('d:\mm.xlsx')#創建一個excel文件
worksheet=workbook.add_worksheet()#創建一個sheet

title=[u'賬號',u'密碼']#設置表格title
worksheet.write_row('A1',title) #將title寫入excel

for i in range(1,100):
    num0=bytes(i+1)#因為默認從0開始,所以要加1
    num=bytes(i)
    row='A'+num0#設置行內容
    data=[u'user'+num,num,]#設置列內容
    worksheet.write_row(row,data)#將內容寫入單元格
    i+=1#換行

workbook.close()#關閉excel

endtime=time.time()#獲取文件關閉時間
print endtime-startime#計算從創建到寫入完成總花費時間

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM