python 讀寫 Excel文件


 一、用xlrd和xlwt讀寫excel

    首先下載安裝xlrd和xlwt這兩個庫。

  1、打開excel

    readbook = xlrd.open_workbook(r'\test\canying.xlsx')

  2、獲取讀入的文件的sheet

    sheet = readbook.sheet_by_index(1)#索引的方式,從0開始     sheet = readbook.sheet_by_name('sheet2')#名字的方式

  3、獲取sheet的最大行數和列數

    nrows = sheet.nrows#行     ncols = sheet.ncols#列

  4、獲取某個單元格的值

    lng = table.cell(i,3).value#獲取i行3列的表格值     lat = table.cell(i,4).value#獲取i行4列的表格值

  5、打開將寫的表並添加sheet

    writebook = xlwt.Workbook()#打開一個excel     sheet = writebook.add_sheet('test')#在打開的excel中添加一個sheet

  6、將數據寫入excel

     sheet.write(i,0,result[0])#寫入excel,i行0列     sheet.write(i,1,result[1])

  7、保存

     writebook.save('answer.xls')#一定要記得保存

  相關代碼

# coding=utf-8
import xlrd
import xlwt
import datetime

import os

class excelProcess:
    def __init__(self,keywordExcelFile,mainExcelFile):
        self.keywordExcelFile = keywordExcelFile
        self.mainExcelFile = mainExcelFile

    def WriteLog(self, message,date):
        fileName = os.path.join(os.getcwd(),  date  +   '.txt')
        with open(fileName, 'a') as f:
            f.write(message)

    def WriteSheetRow(self,sheet, rowValueList, rowIndex, isBold):
        i = 0
        style = xlwt.easyxf('font: bold 1')
        # style = xlwt.easyxf('font: bold 0, color red;')#紅色字體
        # style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 設置Excel單元格的背景色為黃色,字體為粗體
        for svalue in rowValueList:
            if isBold:
                sheet.write(rowIndex, i, svalue, style)
            else:
                sheet.write(rowIndex, i, svalue)
            i = i + 1

    def save_Excel(self):
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('sheet1', cell_overwrite_ok=True)
        headList = ['IR_SITENAME', 'IR_AUTHORS', 'SY_INFOTYPE', 'RID', 'IR_URLTITLE','SY_KEYWORDS',
                    'IR_URLNAME', 'IR_URLTIME',
                    'IR_GROUPNAME', 'IR_CHANNEL',
                    'SY_BB_COMMON', 'summary', 'keyword'
                    ]

        rowIndex = 0
        self.WriteSheetRow(sheet, headList, rowIndex, True)
        for i in range(1, 11):
            rowIndex = rowIndex + 1
            valueList = []
            for j in range(1, 14):
                valueList.append(j * i)
            self.WriteSheetRow(sheet, valueList, rowIndex, False)
        fileName = os.path.join(os.getcwd(),'test.xlsx')
        wbk.save(fileName)
View Code

 

import openpyxl


def readExel():
    filename = r'頁面檢測.xlsx'
    inwb = openpyxl.load_workbook(filename)  # 讀文件
    print(inwb)
    sheetnames = inwb.get_sheet_names()  # 獲取讀文件中所有的sheet,通過名字的方式
    print(sheetnames)
    ws = inwb.get_sheet_by_name(sheetnames[0])  # 獲取第一個sheet內容

    # 獲取sheet的最大行數和列數
    # 最大行數
    rows = ws.max_row
    print(rows)
    # 最大列數
    cols = ws.max_column + 1
    print(cols)
    for r in range(3, rows):
        temp_data = [ws.cell(r, c).value for c in range(1, cols)]
        print(len(temp_data), temp_data)
        # print(temp_data)
函數

 

  二、使用openpyxl庫讀寫excel

    xlrd和xlwt處理的是xls文件,單個sheet最大行數是65535,如果有更大需要的,建議使用openpyxl函數,最大行數達到1048576。 
    如果數據量超過65535就會遇到:ValueError: row index was 65536, not allowed by .xls format

    首先需要導入 import openpyxl

    1、打開excel

      

    2、獲取打開的excel的sheet內容

 

       

    3、獲取sheet的最大行數和列數

      

    4、獲取某個單元格的值

      print(ws.cell(1,1).value)

    5、打開將寫的表並添加sheet

      

    6、保存

      

 

     完整代碼

    def readExel(self):
        filename = r'D:\work\Excel_txtProcesss\new-微博-合並\58.xlsx'
        inwb = openpyxl.load_workbook(filename)  # 讀文件

        sheetnames = inwb.get_sheet_names()  # 獲取讀文件中所有的sheet,通過名字的方式
        ws = inwb.get_sheet_by_name(sheetnames[0])  # 獲取第一個sheet內容

        # 獲取sheet的最大行數和列數
        rows = ws.max_row
        cols = ws.max_column
        for r in range(1,rows):
            for c in range(1,cols):
                print(ws.cell(r,c).value)
            if r==10:
                break

    def writeExcel(self):
        outwb = openpyxl.Workbook()  # 打開一個將寫的文件
        outws = outwb.create_sheet(index=0)  # 在將寫的文件創建sheet
        for row in range(1,70000):
            for col in range(1,4):
                outws.cell(row, col).value = row*2  # 寫文件
            print(row)
        saveExcel = "D:\\work\\Excel_txtProcesss\\test.xlsx"
        outwb.save(saveExcel)  # 一定要記得保存

 

 

 三、

  style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;')

  在設置上Excel單元格的背景色時,fore_colour 支持的顏色是有限的,僅支持一下顏色

  aqua 0x31
  black 0x08
  blue 0x0C
  blue_gray 0x36
  bright_green 0x0B
  brown 0x3C
  coral 0x1D
  cyan_ega 0x0F
  dark_blue 0x12
  dark_blue_ega 0x12
  dark_green 0x3A
  dark_green_ega 0x11
  dark_purple 0x1C
  dark_red 0x10
  dark_red_ega 0x10
  dark_teal 0x38
  dark_yellow 0x13
  gold 0x33
  gray_ega 0x17
  gray25 0x16
  gray40 0x37
  gray50 0x17
  gray80 0x3F
  green 0x11
  ice_blue 0x1F
  indigo 0x3E
  ivory 0x1A
  lavender 0x2E
  light_blue 0x30
  light_green 0x2A
  light_orange 0x34
  light_turquoise 0x29
  light_yellow 0x2B
  lime 0x32
  magenta_ega 0x0E
  ocean_blue 0x1E
  olive_ega 0x13
  olive_green 0x3B
  orange 0x35
  pale_blue 0x2C
  periwinkle 0x18
  pink 0x0E
  plum 0x3D
  purple_ega 0x14
  red 0x0A
  rose 0x2D
  sea_green 0x39
  silver_ega 0x16
  sky_blue 0x28
  tan 0x2F
  teal 0x15
  teal_ega 0x15
  turquoise 0x0F
  violet 0x14
  white 0x09
  yellow 0x0D"""

另外一種方式是 用
pyExcelerator
 
         
View Code
 
         

 


免責聲明!

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



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