Python操作Excel

Posted Carlos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python操作Excel相关的知识,希望对你有一定的参考价值。

excel文件内容:

 

读取excel:

复制代码
# coding=utf-8
import xlrd
import sys

reload(sys)
sys.setdefaultencoding(\'utf-8\')
import traceback


class excelHandle:
    def decode(self, filename, sheetname):
        try:
            filename = filename.decode(\'utf-8\')
            sheetname = sheetname.decode(\'utf-8\')
        except Exception:
            print traceback.print_exc()
        return filename, sheetname

    def read_excel(self, filename, sheetname):
        filename, sheetname = self.decode(filename, sheetname)
        rbook = xlrd.open_workbook(filename)
        sheet = rbook.sheet_by_name(sheetname)
        rows = sheet.nrows
        cols = sheet.ncols
        all_content = []
        for i in range(rows):
            row_content = []
            for j in range(cols):
                cell = sheet.cell_value(i, j)
                row_content.append(cell)
            all_content.append(row_content)
            print \'[\' + \',\'.join("\'" + str(element) + "\'" for element in row_content) + \']\'
        return all_content


if __name__ == \'__main__\':
    eh = excelHandle()
    filename = r\'G:\\test\\ctype.xls\'
    sheetname = \'Sheet1\'
    eh.read_excel(filename, sheetname)
复制代码

输出:

[\'整形\',\'175.0\']
[\'字符串\',\'最后的骑士\']
[\'浮点型\',\'6.23\']
[\'日期\',\'42909.6461574\']
[\'空值\',\'\']
[\'布尔型\',\'1\']

可以看到,数字一律按浮点型输出,日期却输出成一串小数?!布尔型输出0或1

 

代码稍做改动:来看一看表格的数据类型

复制代码
        for i in range(rows):
            row_content = []
            for j in range(cols):
                ctype = sheet.cell(i, j).ctype #表格的数据类型
                print ctype,
                cell = sheet.cell_value(i, j)
                row_content.append(cell)
            all_content.append(row_content)
            print
            print \'[\' + \',\'.join("\'" + str(element) + "\'" for element in row_content) + \']\'
复制代码

输出:

复制代码
1 2
[\'整形\',\'175.0\']
1 1
[\'字符串\',\'最后的骑士\']
1 2
[\'浮点型\',\'6.23\']
1 3
[\'日期\',\'42909.6461574\']
1 0
[\'空值\',\'\']
1 4
[\'布尔型\',\'1\']
复制代码

python读取excel中单元格的内容返回的有5种类型,即上面例子中的ctype:


ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

 

所以,判断一下ctype,然后再做相应处理就可以了。

 

最终代码:

复制代码
# coding=utf-8
import xlrd
import sys

reload(sys)
sys.setdefaultencoding(\'utf-8\')
import traceback
from datetime import datetime
from xlrd import xldate_as_tuple


class excelHandle:
    def decode(self, filename, sheetname):
        try:
            filename = filename.decode(\'utf-8\')
            sheetname = sheetname.decode(\'utf-8\')
        except Exception:
            print traceback.print_exc()
        return filename, sheetname

    def read_excel(self, filename, sheetname):
        filename, sheetname = self.decode(filename, sheetname)
        rbook = xlrd.open_workbook(filename)
        sheet = rbook.sheet_by_name(sheetname)
        rows = sheet.nrows
        cols = sheet.ncols
        all_content = []
        for i in range(rows):
            row_content = []
            for j in range(cols):
                ctype = sheet.cell(i, j).ctype  # 表格的数据类型
                cell = sheet.cell_value(i, j)
                if ctype == 2 and cell % 1 == 0:  # 如果是整形
                    cell = int(cell)
                elif ctype == 3:
                    # 转成datetime对象
                    date = datetime(*xldate_as_tuple(cell, 0))
                    cell = date.strftime(\'%Y/%d/%m %H:%M:%S\')
                elif ctype == 4:
                    cell = True if cell == 1 else False
                row_content.append(cell)
            all_content.append(row_content)
            print \'[\' + \',\'.join("\'" + str(element) + "\'" for element in row_content) + \']\'
        return all_content


if __name__ == \'__main__\':
    eh = excelHandle()
    filename = r\'G:\\test\\ctype.xls\'
    sheetname = \'Sheet1\'
    eh.read_excel(filename, sheetname)
复制代码

输出:

[\'整形\',\'175\']
[\'字符串\',\'最后的骑士\']
[\'浮点型\',\'6.23\']
[\'日期\',\'2017/23/06 15:30:28\']
[\'空值\',\'\']
[\'布尔型\',\'True\']

 

Python读取Excel
import xlrd

xlsFile = xlrd.open_workbook(FilePath)
xlsFile.sheet_names() //返回所有的分表的名字
book = xlsFile.sheet_by_index(index) //按照索引读取表格
book.nrows book.ncols 行和列
cel=book.cell(row, col) //表格的元素
type = cel.ctype //表格的类型
type的类型对应的不同的值
ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

 

二、使用介绍

  1、导入模块

      import xlrd

   2、打开Excel文件读取数据

       data = xlrd.open_workbook(\'excelFile.xls\')

   3、使用技巧

        获取一个工作表

 

        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)
 
单元格
cell_A1 = table.cell(0,0).value
 
cell_C4 = table.cell(2,3).value
 
使用行列索引
cell_A1 = table.row(0)[0].value
 
cell_A2 = table.col(1)[0].value
 
简单的写入
row = 0
 
col = 0
 
# 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype = 1 value = \'单元格的值\'
 
xf = 0 # 扩展的格式化
 
table.put_cell(row, col, ctype, value, xf)
 
table.cell(0,0)  #单元格的值\'
 
table.cell(0,0).value #单元格的值\'

更多操作excel可参考:http://www.2cto.com/kf/201501/373655.html

以上是关于Python操作Excel的主要内容,如果未能解决你的问题,请参考以下文章

python如何操作excel 基础代码

python如何操作excel 基础代码

学习笔记:python3,代码片段(2017)

phpExcel 操作示例

尝试将 Vlookup 片段添加到我的 Excel 宏

Python操作Excel