各位用户为了找寻关于Python读取Excel的方法实例分析的资料费劲了很多周折。这里教程网为您整理了关于Python读取Excel的方法实例分析的相关资料,仅供查阅,以下为您介绍关于Python读取Excel的方法实例分析的详细内容
本文实例讲述了Python读取Excel的方法。分享给大家供大家参考。具体如下:
今天需要从一个Excel文档(.xls)中导数据到数据库的某表,开始是手工一行行输的。后来想不能一直这样,就用Python写了下面的代码,可以很方便应对这种场景。比如利用我封装的这些方法可以很方便地生成导入数据的SQL。 当然熟悉Excel编程的同学还可以直接用VBA写个脚本生成插入数据的SQL。
还可以将.xls文件改为.csv文件,然后通过SQLyog或者Navicat等工具导入进来,但是不能细粒度控制(比如不满足某些条件的某些数据不需要导入,而用程序就能更精细地控制了;又比如重复数据不能重复导入;还有比如待导入的Excel表格和数据库中的表的列不完全一致) 。
我的Python版本是3.0,需要去下载xlrd 3: http://pypi.python.org/pypi/xlrd3/ 然后通过setup.py install命令安装即可
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69import
xlrd3
'''
author: jxqlove?
本代码主要封装了几个操作Excel数据的方法
'''
'''
获取行视图
根据Sheet序号获取该Sheet包含的所有行,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
def
getAllRowsBySheetIndex(sheetIndex, xlsFilePath):
workBook
=
xlrd3.open_workbook(xlsFilePath)
table
=
workBook.sheets()[sheetIndex]
rows
=
[]
rowNum
=
table.nrows
# 总共行数
rowList
=
table.row_values
for
i
in
range
(rowNum):
rows.append(rowList(i))
# 等价于rows.append(i, rowLists(i))
return
rows
'''
获取某个Sheet的指定序号的行
sheetIndex从0开始
rowIndex从0开始
'''
def
getRow(sheetIndex, rowIndex, xlsFilePath):
rows
=
getAllRowsBySheetIndex(sheetIndex, xlsFilePath)
return
rows[rowIndex]
'''
获取列视图
根据Sheet序号获取该Sheet包含的所有列,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
def
getAllColsBySheetIndex(sheetIndex, xlsFilePath):
workBook
=
xlrd3.open_workbook(xlsFilePath)
table
=
workBook.sheets()[sheetIndex]
cols
=
[]
colNum
=
table.ncols
# 总共列数
colList
=
table.col_values
for
i
in
range
(colNum):
cols.append(colList(i))
return
cols
'''
获取某个Sheet的指定序号的列
sheetIndex从0开始
colIndex从0开始
'''
def
getCol(sheetIndex, colIndex, xlsFilePath):
cols
=
getAllColsBySheetIndex(sheetIndex, xlsFilePath)
return
cols[colIndex]
'''
获取指定sheet的指定行列的单元格中的值
'''
def
getCellValue(sheetIndex, rowIndex, colIndex, xlsFilePath):
workBook
=
xlrd3.open_workbook(xlsFilePath)
table
=
workBook.sheets()[sheetIndex]
return
table.cell(rowIndex, colIndex).value
# 或者table.row(0)[0].value或者table.col(0)[0].value
if
__name__
=
=
'__main__'
:
rowsInFirstSheet
=
getAllRowsBySheetIndex(
0
,
'./产品.xls'
)
print
(rowsInFirstSheet)
colsInFirstSheet
=
getAllColsBySheetIndex(
0
,
'./产品.xls'
)
print
(colsInFirstSheet)
print
(getRow(
0
,
0
,
'./产品.xls'
))
# 获取第一个sheet第一行的数据
print
(getCol(
0
,
0
,
'./产品.xls'
))
# 获取第一个sheet第一列的数据
print
(getCellValue(
0
,
3
,
2
,
'./产品.xls'
))
# 获取第一个sheet第四行第二列的单元格的值
希望本文所述对大家的Python程序设计有所帮助。