python 读写 excel

本文介绍了如何使用Python的xlrd和xlwt库进行Excel数据的读取和写入。通过示例代码展示了读取Excel文件、创建新工作表并写入数据的操作,同时提到了xlwt的行限制及解决方案。

      帮朋友写一个excel数据处理脚本,顺便熟悉下python的excel操作


读取excel使用xlrd

下载地址:

http://pypi.python.org/pypi/xlrd

http://www.lexicon.net/sjmachin/xlrd.htm

使用例子:

import xlrd
    book = xlrd.open_workbook("myfile.xls")
    print "The number of worksheets is", book.nsheets
    print "Worksheet name(s):", book.sheet_names()
    sh = book.sheet_by_index(0)
    print sh.name, sh.nrows, sh.ncols
    print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
    for rx in range(sh.nrows):
        print sh.row(rx)

写入excel使用xlwt,我使用的是xlwt-future-0.8.0,这个支持xlsx

下载地址:

http://pypi.python.org/pypi/xlwt-future

使用例子:

#write work book

outWorkbook = xlwt.Workbook(encoding = 'utf-8')

outsheet = outWorkbook.add_sheet('outcode')

outsheet.write(0, 0, label = 'Row 0, Column 0 Value')

outWorkbook.save('out_Workbook.xls')

需要注意的是:他的一个工作表sheet只能写入65535行,多了就不能写了,解决方法可以是,每65535行新建一个工作表sheet或者向后移动几列,

然后写入,他的列最大值为256,所以最多一个sheet文件可以写入:256 * 65535 个数据


以下附上我的代码例子:

#Auther: lancer

#Data: 2016-01

#Function: ProcessCode

#Version: 1.00


import os

import re

import shutil

import string


#read excel

import xlrd

#write excel

import xlwt


#col defines

COL_LABEL = 0

COL_SCL = 1

COL_SDA = 2

COL_Comment = 3


#mode defines

MODE_COPY = 0

MODE_WRITE = 1


#write work book

outWorkbook = xlwt.Workbook(encoding = 'utf-8')

outsheet = outWorkbook.add_sheet('outcode')

#outsheet.write(0, 0, label = 'Row 0, Column 0 Value')


data = xlrd.open_workbook('Code1023.xlsx')

#

##get worksheet

##table = data.sheets()[0]

##table = data.sheet_by_index(0)

table = data.sheet_by_name(u'Sheet1')

##

##table.row_values(i)

##table.col_values(i)

##

##

##

##    nrows = table.nrows

##        

##        ncols = table.ncols

##        

##

##        for i in range(nrows ):

##            print table.row_values(i)

##

#

##get cell

#cell_A1 = table.cell(0,0).value

#

#print cell_A1

#

#cell_2d = table.cell(2,3).value

#

#print cell_2d

#

#ncols = table.nrows

#

#print ncols

#

#inputSheet = data.sheet_by_name(u'Sheet_in')

#outSheet = data.sheet_by_name(u'Sheet_out')


def processOneCode(code, start, end, rows):

    st3end = 274


    outStart = (st3end - start) * code + start

    mode = MODE_COPY

    byteIndex = 0

    xIndex = 0

    print code

#    print outStart


    colStart = code/rows*5

    if code/rows > 0:

        outStart = (code%rows) * (st3end - start)

#        print "---outstart", outStart

    #label only need to write once

    outsheet.write(outStart, COL_LABEL+colStart, label = 'Code' + str(code) + '_ST2')


    outrow = outStart

#write step 2

    for i in range(start, end):

#        print "i", i

#        print "outstart", outStart

        outrow = outStart + i - start

#        print "outrow", outrow

#        outsheet.write(outrow, COL_LABEL, label = table.cell(i, COL_LABEL).value)

        outsheet.write(outrow, COL_SCL+colStart, label = table.cell(i, COL_SCL).value)

        #write comment

        commentValue = table.cell(i, COL_Comment).value

        outsheet.write(outrow, COL_Comment+colStart, label = commentValue)

        commentValue = commentValue.strip().upper()

#        print commentValue

        if 'X'==commentValue:

            xIndex += 1

#            print "find x:" + commentValue + str(xIndex)


        if mode == MODE_COPY:

            outsheet.write(outrow, COL_SDA+colStart, label = table.cell(i, COL_SDA).value)

            if xIndex==2:

                mode = MODE_WRITE

                xIndex = 0

        else:

            if 'X'==commentValue or 'ACK'==commentValue:

                outsheet.write(outrow, COL_SDA+colStart, label = table.cell(i, COL_SDA).value)

            elif 'STOP'==commentValue:

                outsheet.write(outrow, COL_SDA+colStart, label = table.cell(i, COL_SDA).value)

                mode = MODE_COPY

            else:

                byteIndex += 1

#                if code != 0:

#                    print str(code) + 'code:', (code >> (10-byteIndex)) & 1

                outsheet.write(outrow, COL_SDA+colStart, label = (code >> (10-byteIndex)) & 1)

                if byteIndex == 10:

                    byteIndex = 0


#write step3

    outStart = outStart + end - start

#    print "step3 start:",outStart

    outsheet.write(outStart, COL_LABEL+colStart, label = 'Code' + str(code) + '_ST3')

    for i in range(end, st3end):

        outrow = outStart + i - end

        outsheet.write(outrow, COL_SCL+colStart, label = table.cell(i, COL_SCL).value)

        outsheet.write(outrow, COL_SDA+colStart, label = table.cell(i, COL_SDA).value)

        outsheet.write(outrow, COL_Comment+colStart, label = table.cell(i, COL_Comment).value)


#write before process

for i in range (32):

    for j in range (4):

        outsheet.write(i, j, label = table.cell(i, j).value)


#write insert process

for k in range (0, 1024):

    processOneCode(k, 32, 243, 200)


#for i in range (32, 243):

##write col0

#    outsheet.write(i, 0, label = table.cell(i, 0).value)

##write col1

#    outsheet.write(i, 1, label = table.cell(i, 1).value)




#outSheet.cell(i+start, COL_Comment) = tabel.cell(i+start, COL_Comment)


outWorkbook.save('out_Workbook.xls')




Python有多个库可以读写Excel文件,其中比较常用的有: 1. openpyxl:一个用于读写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。 2. xlrd/xlwt:用于读写Excel 97-2003 .xls文件的Python库。 3. pandas:pandas库可以读取和入多种文件格式,包括Excel文件。 下面分别介绍使用这三个库的方法: ### 1. 使用openpyxl 安装openpyxl库: ``` pip install openpyxl ``` 读取Excel文件: ```python from openpyxl import load_workbook # 打开Excel文件 wb = load_workbook(filename='example.xlsx', read_only=True) # 选择工作表 ws = wb['Sheet1'] # 读取单元格数据 cell_value = ws.cell(row=1, column=1).value print(cell_value) # 遍历行 for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): for cell in row: print(cell.value) # 遍历列 for col in ws.iter_cols(min_row=1, max_col=3, max_row=2): for cell in col: print(cell.value) # 读取整个工作表的数据,返回一个嵌套列表 data = [] for row in ws.iter_rows(min_row=1): row_data = [] for cell in row: row_data.append(cell.value) data.append(row_data) print(data) ``` Excel文件: ```python from openpyxl import Workbook # 创建Excel文件 wb = Workbook() # 选择工作表 ws = wb.active # 入单元格数据 ws['A1'] = 'Hello' ws.cell(row=1, column=2, value='World') # 入多行数据 data = [['Name', 'Age', 'Gender'], ['Tom', 18, 'Male'], ['Lucy', 20, 'Female']] for row in data: ws.append(row) # 保存Excel文件 wb.save('example.xlsx') ``` ### 2. 使用xlrd/xlwt 安装xlrd和xlwt库: ``` pip install xlrd pip install xlwt ``` 读取Excel文件: ```python import xlrd # 打开Excel文件 wb = xlrd.open_workbook('example.xls') # 选择工作表 ws = wb.sheet_by_name('Sheet1') # 读取单元格数据 cell_value = ws.cell_value(0, 0) print(cell_value) # 遍历行 for row in range(ws.nrows): for col in range(ws.ncols): cell_value = ws.cell_value(row, col) print(cell_value) # 读取整个工作表的数据,返回一个嵌套列表 data = [] for row in range(ws.nrows): row_data = [] for col in range(ws.ncols): cell_value = ws.cell_value(row, col) row_data.append(cell_value) data.append(row_data) print(data) ``` Excel文件: ```python import xlwt # 创建Excel文件 wb = xlwt.Workbook() # 选择工作表 ws = wb.add_sheet('Sheet1') # 入单元格数据 ws.write(0, 0, 'Hello') ws.write(0, 1, 'World') # 入多行数据 data = [['Name', 'Age', 'Gender'], ['Tom', 18, 'Male'], ['Lucy', 20, 'Female']] for row, row_data in enumerate(data): for col, cell_value in enumerate(row_data): ws.write(row+1, col, cell_value) # 保存Excel文件 wb.save('example.xls') ``` ### 3. 使用pandas 安装pandas库: ``` pip install pandas ``` 读取Excel文件: ```python import pandas as pd # 读取Excel文件 df = pd.read_excel('example.xlsx', sheet_name='Sheet1') # 读取单元格数据 cell_value = df.iloc[0, 0] print(cell_value) # 遍历行 for index, row in df.iterrows(): print(row['Name'], row['Age'], row['Gender']) # 读取整个工作表的数据,返回一个DataFrame对象 data = df.values.tolist() print(data) ``` Excel文件: ```python import pandas as pd # 创建DataFrame对象 df = pd.DataFrame({'Name': ['Tom', 'Lucy'], 'Age': [18, 20], 'Gender': ['Male', 'Female']}) # Excel文件 df.to_excel('example.xlsx', sheet_name='Sheet1', index=False) ``` 以上是使用Python读写Excel的常用方法,可以根据实际需求选择不同的库和方法。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值