1. 程式人生 > >python xlrd,xlwt 讀寫excel檔案

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, 解壓後安裝:

安裝成功後就可以引用了。如下程式碼:

# -*- coding: utf-8 -*-
import os
import xlrd
import xlwt
import datetime

##################讀excel檔案##############################

#開啟Excel檔案,引數:excelFile:Excel檔案路徑
def open_Excel(excelFile):
  excelFile = unicode(excelFile, "utf8")
  if os.path.isfile(excelFile):
    try:
      data = xlrd.open_workbook(excelFile)
      return data
    except Exception,e:
      print str(e)

'''往EXCEl單元格寫內容,每次寫一行sheet:頁簽名稱;row:行內容列表;rowIndex:行索引;
isBold:true:粗欄位,false:普通字型'''
def WriteSheetRow(sheet,rowValueList,rowIndex,isBold):
  i = 0
  style = xlwt.easyxf('font: bold 1') #粗字型

  #style = xlwt.easyxf('font: bold 1, color red;') #紅色字型
  for svalue in rowValueList:
    strValue = unicode(str(svalue),'utf-8')
    if isBold:
      sheet.write(rowIndex,i,strValue,style)
    else:
      sheet.write(rowIndex,i,strValue)
    i = i + 1

#根據索引獲取Excel表格中的資料 引數:excelFile:Excel檔案路徑 ,by_index:表的索引
def open_Excel_ByIndex(excelFile,sheetIndex):
  data = open_Excel(excelFile)
  table = data.sheets()[sheetIndex]
  nrows = table.nrows #行數
  ncols = table.ncols #列數
  cursor = getSqlCursor()
  for i in xrange(0,nrows):
    headCols = table.row_values(i) #某一行資料 
    for a in headCols:
      print a

#測試
open_Excel_ByIndex("D:\\test.xlsx",0)

#根據名稱獲取Excel表格中的資料 引數:excelFile:Excel檔案路徑 
#sheetName:Sheet1名稱 
def open_Excel_BySheetName(excelFile,sheetName):
  sheetName = unicode(sheetName, "utf8")
  data = open_Excel(excelFile)
  table = data.sheet_by_name(sheetName)
  nrows = table.nrows #行數
  ncols = table.ncols #列數
  cursor = getSqlCursor()
  for i in xrange(0,nrows):
    headCols = table.row_values(i) #某一行資料 
    for a in headCols:
      print a
#測試
open_Excel_BySheetName("D:\\test.xlsx",'sheet1')

##################寫excel檔案##############################
'''寫excel檔案''' 
def save_Excel(strFile):
  excelFile = unicode(strFile, "utf8")
  wbk = xlwt.Workbook()
  sheet = wbk.add_sheet('sheet1')
  headList = ['標題1','標題2','標題3','標題4']
  rowIndex = 0
  WriteSheetRow(sheet,headList,rowIndex,,True)
  for i in xrange(1,11):
    rowIndex = rowIndex + 1
    valueList = []
    for j in xrange(1,5):
      valueList.append(j*i)
    WriteSheetRow(sheet,valueList,rowIndex,False)
  wbk.save(excelFile)

#測試
save_Excel("D:\\test.xlsx")

結果如下:

##################單元格常用設定##############################

1、設定超連結

  #設定超連結
  

  font = xlwt.Font() # Create Font
  font.colour_index = 4 # 藍色字型
  font.underline=True
  style = xlwt.XFStyle()
  style.font = font
  sheet.write(rowIndex,4,xlwt.Formula('HYPERLINK("https://www.baidu.com";"baidu")'),style)

2、設定單元格背景色

  #設定單元格背景色 
  pattern = xlwt.Pattern()
  pattern.pattern = xlwt.Pattern.SOLID_PATTERN
  pattern.pattern_fore_colour = 5 #黃色
  style = xlwt.XFStyle()
  style.pattern = pattern
  sheet.write(5, 5, 'Cell Contents', style)
  ''' 顏色值
  0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 
  5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 
  17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow ,
  20 = Dark Magenta, 21 = Teal,
  22 = Light Gray, 23 = Dark Gray 
  '''

3、設定粗字型

  style = xlwt.easyxf('font: bold 1')

  sheet.write(5, 5, 'Cell Contents', style)

4、設定字型顏色

  style = xlwt.easyxf('font: bold 0, color red;')#紅色字型

  sheet.write(5, 5, 'Cell Contents', style)

5、設定列寬頻

  sheet.col(1).width = 3333 # 3333 = 1" (one inch)

6、設定日期格式

  style = xlwt.XFStyle()
  style.num_format_str = 'YYYY/MM/DD h:mm:ss' 
  sheet.write(5, 5, datetime.datetime.now(), style)

  

  #Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss,
  # M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0

7、合併行和列

  sheet.write_merge(0, 0, 0, 3, 'First Merge')

  sheet.write_merge(2, 4, 0, 3, 'Second Merge')

  

8、給單元格增加邊框 

  borders = xlwt.Borders() # Create Borders
  borders.left = xlwt.Borders.DASHED

  # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED,   THIN_DASH_DOTTED,              #MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED,

  #SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
  borders.right = xlwt.Borders.DASHED
  borders.top = xlwt.Borders.DASHED
  borders.bottom = xlwt.Borders.DASHED
  borders.left_colour = 0x40
  borders.right_colour = 0x40
  borders.top_colour = 0x40
  borders.bottom_colour = 0x40
  style = xlwt.XFStyle() # Create Style
  style.borders = borders # Add Borders to Style

  

9、設定單元格中內容中位置,居中,局左右等

  alignment = xlwt.Alignment() # Create Alignment
  # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, 
  #HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
  alignment.horz = xlwt.Alignment.HORZ_CENTER   #水平居中
  # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
  alignment.vert = xlwt.Alignment.VERT_CENTER    #垂直居中
  style = xlwt.XFStyle() # Create Style
  style.alignment = alignment # Add Alignment to Style
  sheet.write(5, 5, 'Cell Contents', style)

  

閱讀原文

原文:https://www.cnblogs.com/276815076/p/8028127.html