1. 程式人生 > >Python簡單讀寫Excel (xlwt, xlrd, xlutils)

Python簡單讀寫Excel (xlwt, xlrd, xlutils)

#!/usr/bin/env python
#coding=utf8
####################################################################################
#
#此程式是為了將excel中的一列單元格的中的某些數字不夠三位的補零,如cell: abc_12_cd -> abc_012_cd
#涉及讀寫整個excel表,和改寫excel部分單元格的內容
#
####################################################################################


import xlwt #Need install xlwt, create excel and write
import xlrd #Need install xlrd, read excel
from datetime import datetime #date covert
from xlutils.copy import copy #此module是開啟excel檔案後直接寫入要改寫cell,need install xlutils(relay on xlwt,xlrd)

style_backGreen_fontBlack_boldYes = xlwt.easyxf('align: horz center; font: name Times New Roman, color-index black, bold on, height 250; pattern: pattern solid, fore_colour light_green; borders: left 1, right 1, top 1, bottom 1;')
style_backGreen_fontBlack_boldYes_header = xlwt.easyxf('align: horz center; font: name Times New Roman, color-index black, bold on, height 300; pattern: pattern solid, fore_colour bright_green; borders: left 1, right 1, top 1, bottom 1;')
style_backYellow_fontBlack_boldNo = xlwt.easyxf('align: horz center; font: name Times New Roman, color-index black, bold off, height 250; pattern: pattern solid, fore_colour light_yellow; borders: left 1, right 1, top 1, bottom 1;')
style_backGray25_fontBlack_boldNo = xlwt.easyxf('align: horz center; font: name Times New Roman, color-index black, bold off, height 250; pattern: pattern solid, fore_colour gray25; borders: left 1, right 1, top 1, bottom 1;')
style_backwhite_fontBlack_boldNo = xlwt.easyxf('align: horz center; font: name Times New Roman, color-index black, bold off, height 250; pattern: pattern solid, fore_colour white; borders: left 1, right 1, top 1, bottom 1;')

def createExcelHandler(sheetName):
    wb = xlwt.Workbook()
    ws = wb.add_sheet(sheetName, cell_overwrite_ok=True)
    return wb, ws

def readXlsAndChange(readFileName, sheetName):
    mWorkBook = xlrd.open_workbook(readFileName, formatting_info = False) #開啟一個excel表,並保持格式
    (wb, ws) = createExcelHandler(sheetName) #建立一個excel表,建立一個sheet
    #mSheet = mWorkBook.sheets()[0] #取一個excel表的第一個sheet
    #mRowData = mSheet.row_values(1) #獲取一行excel資料
    #mRowDataCell = mRowData[1].split('_') #獲取第二個cell的值
    
    mSheet = mWorkBook.sheets()[0]
    mStationChange = []
    mStationChange.append('Station')
    for index, station in enumerate(mSheet.col_slice(1, 0, None)): #從第二列,第一行往下讀
        #print station
        if index == 0: #第一行儲存的是"station"使用split後會造成後續的list range out
            continue
        mStationChange.append(station)
        mStationChangeCell = mStationChange[index].value.encode('utf-8').split('_') #獲取單元格的內容 .value.encode('utf-8').split('_')
        #print mStationChangeCell
        mStationChangeCell[2] = mStationChangeCell[2].zfill(3) #29->029
        mStationChange[index] = '_'.join(mStationChangeCell)
        #print mStationChange[index]
    
    for rowIndex, mRowData in enumerate(mSheet.get_rows()):
        #print mRowData
        for colIndex, cellData in enumerate(mRowData):
            if (cellData.ctype == 3): # 日期type為3, ctype :  0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                date_value = xlrd.xldate_as_tuple(cellData.value, mWorkBook.datemode)
                #print date_value #(2016, 1, 10, 3, 53, 23)
                date_tmp = datetime(*date_value[:6])             #2016-01-10 03:59:01
                #date_tmp = datetime(*date_value[:6]).isoformat() #2016-01-10T03:59:01
                #print date_tmp
                ws.write(rowIndex, colIndex, date_tmp, style_backwhite_fontBlack_boldNo) #日期不轉換的話可以自己使用excel中的日期調節
            elif colIndex == 1:
                ws.write(rowIndex, colIndex, mStationChange[rowIndex], style_backwhite_fontBlack_boldNo)
            else:
                ws.write(rowIndex, colIndex, cellData.value, style_backwhite_fontBlack_boldNo)
    print '/'.join(readFileName.split('/')[0:-1])  + '/new_' + readFileName.split('/')[-1]
    wb.save('/'.join(readFileName.split('/')[0:-1])  + '/new_' + readFileName.split('/')[-1].split('.')[0] + '.xls') #不知為何只能儲存.xls格式的excel,xlsx格式建立後打不開
    print "Function readXlsAndChange Done!"

    #print string.zfill(int(mRowData[1].split('_')[2], base=10), 3) #變換為數字

def copyAndRewrite(readFileName):
    mWorkBook = xlrd.open_workbook(readFileName, formatting_info = False) #開啟一個excel表,並保持格式
    msheetNo1 = mWorkBook.sheets()[0]
    
    newWorkBook = copy(mWorkBook) #複製一個workbook,是可以重寫的
    newSheetNo1 = newWorkBook.get_sheet(0) #得到一個sheet,然後寫入指定位置,其它不變
    
    mStationChange = []
    mStationChange.append('Station')
    for index, station in enumerate(msheetNo1.col_slice(1, 0, None)): #從第二列,第一行往下讀
        #print station
        if index == 0: #第一行儲存的是"station"使用split後會造成後續的list range out
            continue
        mStationChange.append(station)
        mStationChangeCell = mStationChange[index].value.encode('utf-8').split('_') #獲取單元格的內容 .value.encode('utf-8').split('_')
        #print mStationChangeCell
        mStationChangeCell[2] = mStationChangeCell[2].zfill(3) #29->029
        mStationChange[index] = '_'.join(mStationChangeCell)
        #print mStationChange[index]
    
    for rowIndex, mCellData in enumerate(mStationChange):
        newSheetNo1.write(rowIndex, 1, mCellData)
    newWorkBook.save('/'.join(readFileName.split('/')[0:-1])  + '/new_' + readFileName.split('/')[-1].split('.')[0] + '.xls') #不知為何只能儲存.xls格式的excel,xlsx格式建立後打不開
    print "Function copyAndRewrite Done!"
    
if __name__ == "__main__":
    readXlsAndChange("./abc/testZero.xlsx", "Retest_Item")
    #copyAndRewrite("./abc/testZero.xlsx")


原excel:


用函式readXlsAndChange處理後生成新的excel:


用函式copyAndRewrite處理後的excel:


相關推薦

Python簡單Excel (xlwt, xlrd, xlutils)

#!/usr/bin/env python #coding=utf8 #################################################################################### # #此程式是為了將excel中的

pythonexcelxlrdxlwt

1 Examples Generating Excel Documents Using Python’s xlwt 2 3 Here are some simple examples using Python’s xlwt library to dynamically generate

pythonexcel並存入mysql

xxxxx 指定 pytho 一個 讀寫 連接 size mysq 亂碼 為了一個突如其來的想法:用python簡單解決就好。現在算是把這個項目需要的基礎功能坑都填完了。剩下就是AI和數據展示方面的坑了。 今天遇到的坑是: 1、從excel讀出的中文

pythonexcel

轉載:http://blog.csdn.net/majordong100/article/details/50708365 學習Python的過程中,我們會遇到Excel的讀寫問題。通過搜尋得知,我們可以使用xlwt module將資料寫入Excel表格,使用xlrd module從Ex

python->excel

from openpyxl import load_workbook#將一個excel文件中的資料存放記憶體中,即變數wb儲存了該excel的所有資訊wb = load_workbook(r"D:\ee_cwmp_plh.xlsx")#選中文件中的一個datasheetws = wb['TR-098 Data

c#操作excel方式一:stream簡單excel

需要名稱空間 using System.IO; 介面: 記得新增openFileDialog 注意名字,改成跟程式碼裡的對應 寫檔案按鈕程式碼: private void button2_Click(object sender, EventArgs e)

python openpyxlexcel

python有多類可以讀寫excel的包。openpyxl函式功能較全,可以讀寫2007版本的excel。 下面列舉常用的讀寫方法。 #匯入open <pre name="code" class="python">from openpyxl import Wo

pythonexcel

一 讀取excel 這裡介紹一個不錯的包xlrs,可以工作在任何平臺。這也就意味著你可以在Linux下讀取Excel檔案。 首先,開啟workbook;     import xlrd wb = xlrd.open_workbook('myworkbook.xls') 檢查表單名字:     wb.she

Npoi簡單Excel

imp con tex play hive 分享 fin tails npoi 什麽是NPOI ?   簡而言之,NPOI就是可以在沒有Office的情況下對Word或Excel文檔進行讀寫等操作。 使用方式 :   1、準備NPOI的dll文件     下載鏈接:

pythonExcel文件--使用xlrd模塊讀取,xlwt模塊寫入

xlrd get sta series 有趣 light log 分享 均值 一、安裝xlrd模塊和xlwt模塊 1. 下載xlrd模塊和xlwt模塊 到python官網http://pypi.python.org/pypi/xlrd下載模塊。下載的文件

pythonexcel的相關操作(xlrdxlwt)

筆者小白在最近的qq記錄分析的任務中需要用到對excel的操作,在這裡做一個總結。 這裡需要指出的是這篇文章總結了 如何利用xlwt新建一個excel檔案,如何利用xlrd只讀一個excel檔案。 在文章的末尾總結了如何讀取一個已經存在的execel檔案,然後再

python xlrd,xlwt excel檔案

python 讀excel檔案,需要xlrd庫。下載地址:https://pypi.python.org/pypi/xlrd python 寫excel檔案,需要xlwt庫。下載地址:https://pypi.python.org/pypi/xlwt/1.1.2 下載後修改副檔名為rar,

Python2.7 xlrd讀取、xlwt寫入、xlutilsExcel表格內容

之前經常用python讀取Excel內容,後來有一段時間不用了再用就給忘記了,覺得記錄還是很有必要的 1. 首選安裝xlrd 安裝方法很簡單,如果裝了pip的話 pip install xlrd 2. python程式碼 實現的功能:將Excel的內容按照字典形式打印

pythonxlrdxlwt模組excel使用詳解

一、xlrd模組和xlwt模組是什麼      xlrd模組是python第三方工具包,用於讀取excel中的資料;      xlwt模組是python第三方工具包,用於往excel中寫入資料; 二、xlrd模組和xlwt模組的安裝 pip in

PythonExcel表格,就是這麼簡單粗暴又好用

最近在做一些資料處理和計算的工作,因為資料是以.csv格式儲存的,因此剛開始直接用Excel來處理。但是做著做著發現重複的勞動其實並沒有多大的意義,於是就想著寫個小工具幫著處理。以前正好在一本書上看到過使用Python來處理Excel表格,可惜沒有仔細看。於是我到處查詢資料,基本解決了日常所需

pythonexcel

字符串 一行 工作 default print file 設置 logs open python讀寫excel: # coding=utf-8 import xlrd import xlwt import traceback from xlutils.copy imp

Pythonexcel表格的方法

python excel 表格 xls 目的:實現用python做excel的讀取、新增、修改操作。環境:ubuntu 16.04 Python 3.5.2用python讀寫文檔,一般是操作txt文件或者可以用記事本打開的文件,因為這個操作很直接,不需要導入其他模塊,但如果想要對excel表

Pythonexcel表格的方法二

python excel 讀寫表格 目的:實現用python的另一種方法做excel的讀取、新增操作。環境:ubuntu 16.04 Python 3.5.2情景:之前介紹了一種操作excel文件的方法(私鏈),現在使用另一種方法讀寫excel文件,一次性讀出或寫入,讀寫也很方便,讀出為有序字典

python excel

excel文件 result rep core read pattern 參數 .sh pri 最近老大讓從網站上獲取數據,手動太慢,網上找了點python,用腳本操作。 1 import os 2 import re 3 4 import xlrd 5 im

Pythonexcel練習_去除excel中亂碼行,並添加列

寫入excel continue delete val value urn com date add 需求: 把app_student.xls裏面的數據, 1、如果這一行數據裏面有亂碼(及包含?),那麽就刪掉 2、再加上一列,是否畢業 3、如果班級是天蠍座