1. 程式人生 > >python讀寫excel

python讀寫excel

字符串 一行 工作 default print file 設置 logs open

python讀寫excel:

# coding=utf-8
import xlrd
import xlwt
import traceback
from xlutils.copy import copy
import sys

reload(sys)
# 需要加上,否則會報UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0-1: ordinal not in range(128)
sys.setdefaultencoding(utf-8)


class ExcelAction:
    ‘‘‘
    只支持xls格式
    
‘‘‘ def transCode(self, filename, sheetname): filename = filename.decode(utf-8) sheetname = sheetname.decode(utf-8) return filename, sheetname def read_excel(self, filename, sheetname): ‘‘‘ 讀取excel ‘‘‘ filename, sheetname = self.transCode(filename, sheetname) workbook
= xlrd.open_workbook(filename) # 獲得工作薄 sheet = workbook.sheet_by_name(sheetname) # 獲得sheet rows = sheet.nrows # 文件總行數 list = [] print u-------文件內容------- for i in range(0, rows): line = sheet.row_values(i) # 獲得一行的值,返回列表 list.append(line)
# 避免打印包含中文的列表時變成unicode print [ + ,.join("" + str(element) + "" for element in line) + ] print u----------------------- return list def write_excel(self, filename, sheetname, row, col, value, type=0): ‘‘‘ 修改excel ‘‘‘ filename, sheetname = self.transCode(filename, sheetname) # 轉成整形是因為要在ride中使用,ride把參數傳過來默認是字符串,除非這樣傳${1} row = int(row) col = int(col) type = int(type) # formatting_info=True保存之前數據的格式 rb = xlrd.open_workbook(filename, formatting_info=True) wb = copy(rb) sheet = wb.get_sheet(sheetname) # 設置樣式,寫入的文字為紅色加粗 style = xlwt.easyxf(font: bold 1, color red;) if type == 1: sheet.write(row, col, value, style) else: sheet.write(row, col, value) wb.save(filename) def addSheet(self, filename, sheetname, row, valueList): ‘‘‘ 寫入excel,一次寫一行 ‘‘‘ filename, sheetname = self.transCode(filename, sheetname) wb = xlwt.Workbook(filename) # 其實會覆蓋第一個sheet頁 sheet = wb.add_sheet(sheetname) for i in range(len(valueList)): # 需要轉碼 valueList[i] = str(valueList[i]).decode(utf-8) sheet.write(row, i, valueList[i]) wb.save(filename) if __name__ == __main__: ea = ExcelAction() filename = rG:\測試數據\最後的騎士.xls sheetname = 第1頁 list = ea.read_excel(filename, sheetname) # ea.write_excel(filename, sheetname, 0, 0, ‘Optimus Prime‘) # ea.write_excel(filename, sheetname, 0, 1, ‘Megatron‘, 1) # valueList = [‘阿杜 - 爛好人‘, ‘阿杜 - 一諾千年‘, ‘Coldplay - Hypnotised‘, ‘Ruth B. - Superficial Love‘, ‘楊宗緯、張碧晨 - 涼涼‘] # ea.addSheet(filename, ‘第2頁‘, 0, valueList)

python讀寫excel