今天需要从一个Excel文档(.xls)中导数据到数据库的某表,开始是手工一行行输的。后来想不能一直这样,就用Python写了下面的代码,可以很方便应对这种场景。比如利用我封装的这些方法可以很方便地生成导入数据的SQL。
当然熟悉Excel编程的同学还可以直接用VBA写个脚本生成插入数据的SQL。
importxlrd3
'''
author: jxqlove?
'''
'''
获取行视图
根据Sheet序号获取该Sheet包含的所有行,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
defgetAllRowsBySheetIndex(sheetIndex, xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]
rows=[]
rowNum=table.nrows# 总共行数
rowList=table.row_values
foriinrange(rowNum):
rows.append(rowList(i))# 等价于rows.append(i, rowLists(i))
returnrows
'''
获取某个Sheet的指定序号的行
sheetIndex从0开始
rowIndex从0开始
'''
defgetRow(sheetIndex, rowIndex, xlsFilePath):
rows=getAllRowsBySheetIndex(sheetIndex, xlsFilePath)
returnrows[rowIndex]
'''
获取列视图
根据Sheet序号获取该Sheet包含的所有列,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
defgetAllColsBySheetIndex(sheetIndex, xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]
cols=[]
colNum=table.ncols# 总共列数
colList=table.col_values
foriinrange(colNum):
cols.append(colList(i))
returncols
'''
获取某个Sheet的指定序号的列
sheetIndex从0开始
colIndex从0开始
'''
defgetCol(sheetIndex, colIndex, xlsFilePath):
cols=getAllColsBySheetIndex(sheetIndex, xlsFilePath)
returncols[colIndex]
'''
获取指定sheet的指定行列的单元格中的值
'''
defgetCellValue(sheetIndex, rowIndex, colIndex, xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]
returntable.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第四行第二列的单元格的值