首页 > 代码库 > 运用Python 读写 Excel

运用Python 读写 Excel

下载第三方包xlrd

pip install xlrdeasy_install xlrd

安装完毕后,分析下面代码

 1 from xlrd import open_workbook 2  3 wb = open_workbook(simple.xls,rb) 4 for s in wb.sheets(): 5     print Sheet:,s.name 6     for row in range(s.nrows): 7         values=[] 8         for col in range(s.ncols): 9             values.append(s.cell(row,col).value)10         print ",".join(values)11     print

wb为表格的对象

sheets()列表形式获取sheet1、sheet2、sheet3...

s代表sheet的对象,

其中s.nrows属性代表sheet的总行数

s.ncols属性代表sheet的总列数

s.cell(x,y)方法代表某一个单元格,其中x是具体的行数,y是具体的列数,可以获取到一个单元的对象

s.cell(x,y).value  .value属性可以获取到单元坐标内的值

 

写xls

from tempfile import TemporaryFilefrom xlwt import Workbookbook = Workbook()sheet1 = book.add_sheet(Sheet 1)book.add_sheet(Sheet 2)sheet1.write(0,0,A1)sheet1.write(0,1,B1)row1 = sheet1.row(1)row1.write(0,A2)row1.write(1,B2)sheet1.col(0).width = 10000sheet2 = book.get_sheet(1)sheet2.row(0).write(0,Sheet 2 A1)sheet2.row(0).write(1,Sheet 2 B1)sheet2.flush_row_data()sheet2.write(1,0,Sheet 2 A3)sheet2.col(0).width = 5000sheet2.col(0).hidden = Truebook.save(simple2.xls)book.save(TemporaryFile())

 

运用Python 读写 Excel