Python 一个简单的读取excel例子

1 准备环境

1.1 安装python

mac上的python默认版本是python2,如下:

hanruikaideMacBook-Pro:local hanruikai$ python
Python 2.7.10 (default, Feb  7 2017, 00:08:15) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D


笔者安装了python3版本,然后IDE安装了Pycharm,感受一下python的开发环境

安装python3后,mac下面的目录是 

hanruikaideMacBook-Pro:bin hanruikai$ pwd
/usr/local/bin
hanruikaideMacBook-Pro:bin hanruikai$ ls 
2to3                    brew                    express                 idle3.6                 npm                     pip3                    pydoc3                  python3                 python3.6               python3.6m              pyvenv
2to3-3.6                easy_install-3.6        idle3                   node                    npx                     pip3.6                  pydoc3.6                python3-config          python3.6-config        python3.6m-config       pyvenv-3.6
hanruikaideMacBook-Pro:bin hanruikai$ 

执行python3命令,可以调用笔者安装的3.X版本的python,不会使用默认的python2版本

执行pip3命令成功,但是pip不行,因为mac自带的 python2没有安装pip,需要单独安装

hanruikaideMacBook-Pro:bin hanruikai$ pip
bash: pip: command not found
hanruikaideMacBook-Pro:bin hanruikai$ pip3

Usage:   
  pip  [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  search                      Search PyPI for packages.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).
  --log                 Path to a verbose appending log.
  --proxy              Specify a proxy in the form [user:passwd@]proxy.server:port.
  --retries          Maximum number of retries each connection should attempt (default 5 times).
  --timeout              Set the socket timeout (default 15 seconds).
  --exists-action     Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host    Mark this host as trusted, even though it does not have valid or any HTTPS.
  --cert                Path to alternate CA bundle.
  --client-cert         Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir            Store the cache data in .
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.
hanruikaideMacBook-Pro:bin hanruikai$

1.2 import excel处理模块

代码第一行先倒入excel处理模块xlrd,如下:

import xlrd


def read_excel():
    # 打开文件
    workbook = xlrd.open_workbook('/Users/hanruikai/Documents/信用卡分类信息表.xlsx')
    # 获取所有sheet
    print(workbook.sheet_names())  # [u'sheet1', u'sheet2']

    # 根据sheet索引或者名称获取sheet内容
    sheet1 = workbook.sheet_by_index(0)  # sheet索引从0开始

    # sheet的名称,行数,列数
    print(sheet1.name, sheet1.nrows, sheet1.ncols)

    # 获取整行和整列的值(数组)
    rows = sheet1.row_values(3)  # 获取第四行内容
    cols = sheet1.col_values(2)  # 获取第三列内容
    print(rows)
    print(cols)

    # 获取单元格内容
    print(sheet1.cell(1, 0).value.encode('utf-8'))
    print(sheet1.cell_value(1, 0).encode('utf-8'))
    print(sheet1.row(1)[0].value.encode('utf-8'))

    # 获取单元格内容的数据类型
    print(sheet1.cell(1, 0).ctype)


if __name__ == '__main__':
    read_excel()

问题来了,导入的xlrd在什么位置?

Python 一个简单的读取excel例子_第1张图片

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages

如果是系统自带的python,会使用dist-packages目录;

如果你手动安装python,它会直接使用目录site-packages。

这允许你让两个安装隔离开来。

dist-packages:系统自带的python

site-packages:自己安装的python

hanruikaideMacBook-Pro:site-packages hanruikai$ ls
README.txt                      easy_install.py                 pip-9.0.3.dist-info             setuptools                      xlrd

__pycache__                     pip                             pkg_resources                   setuptools-39.0.1.dist-info     xlrd-1.1.0.dist-info

2. 运行

pycharm的配置就不在叙述,这个说个问题,运行后没有错误,但是控制台没有输出,很奇怪,后来发现虽然编译没有报错但是print写法不对

  # 打开文件
    workbook = xlrd.open_workbook('/Users/hanruikai/Documents/信用卡分类信息表.xlsx')
    # 获取所有sheet
    print(workbook.sheet_names())  # [u'sheet1', u'sheet2']

上面是正确的写法,原来的写法是,编译器并不报错

  
# 打开文件
workbook = xlrd.open_workbook('/Users/hanruikai/Documents/信用卡分类信息表.xlsx')
# 获取所有sheet
print
workbook.sheet_names() # [u'sheet1', u'sheet2']

3. 发布

hanruikaideMacBook-Pro:bin hanruikai$ pwd
/usr/bin
hanruikaideMacBook-Pro:bin hanruikai$ cd ../local/bin/
hanruikaideMacBook-Pro:bin hanruikai$ ls
2to3                    brew                    express                 idle3.6                 npm                     pip3                    pydoc3                  python3                 python3.6               python3.6m              pyvenv
2to3-3.6                easy_install-3.6        idle3                   node                    npx                     pip3.6                  pydoc3.6                python3-config          python3.6-config        python3.6m-config       pyvenv-3.6
hanruikaideMacBook-Pro:bin hanruikai$ cd python3
bash: cd: python3: Not a directory
hanruikaideMacBook-Pro:bin hanruikai$ pip3 install pyinstaller
Collecting pyinstaller
  Downloading PyInstaller-3.3.1.tar.gz (3.5MB)
    78% |█████████████████████████▏      | 2.7MB 156kB/s eta 0:00:05

安装pyinstaller,进入python安装目录,/usr/local/bin,利用pip3命令安装

hanruikaideMacBook-Pro:eclipse-workspace hanruikai$ ls
Java                            ReadCreditCardExcel.py          flow-platform-aggregator        nodejs                          resources
Mybatis-generator.iml           Test                            mygithub                        puhui-newapp-all                src
hanruikaideMacBook-Pro:eclipse-workspace hanruikai$ pwd
/Users/hanruikai/eclipse-workspace
hanruikaideMacBook-Pro:eclipse-workspace hanruikai$ py
pydoc               pydoc3              pyi-bindepend       pyi-set_version     python-config       python2.7           python3-config      python3.6m          pythonw2.6          pyvenv-3.6          
pydoc2.6            pydoc3.6            pyi-grab_version    pyinstaller         python2.6           python2.7-config    python3.6           python3.6m-config   pythonw2.7          
pydoc2.7            pyi-archive_viewer  pyi-makespec        python              python2.6-config    python3             python3.6-config    pythonw             pyvenv              
hanruikaideMacBook-Pro:eclipse-workspace hanruikai$ pyinstaller  ReadCreditCardExcel.py 
71 INFO: PyInstaller: 3.3.1
72 INFO: Python: 3.6.5
80 INFO: Platform: Darwin-16.7.0-x86_64-i386-64bit
81 INFO: wrote /Users/hanruikai/eclipse-workspace/ReadCreditCardExcel.spec
84 INFO: UPX is not available.
85 INFO: Extending PYTHONPATH with paths
['/Users/hanruikai/eclipse-workspace', '/Users/hanruikai/eclipse-workspace']
85 INFO: checking Analysis
85 INFO: Building Analysis because out00-Analysis.toc is non existent
85 INFO: Initializing module dependency graph...
87 INFO: Initializing module graph hooks...
88 INFO: Analyzing base_library.zip ...
3644 INFO: running Analysis out00-Analysis.toc
3655 INFO: Caching module hooks...
3658 INFO: Analyzing /Users/hanruikai/eclipse-workspace/ReadCreditCardExcel.py
4125 INFO: Loading module hooks...
4125 INFO: Loading module hook "hook-encodings.py"...
4207 INFO: Loading module hook "hook-pydoc.py"...
4208 INFO: Loading module hook "hook-xml.etree.cElementTree.py"...
4209 INFO: Loading module hook "hook-xml.py"...
4493 INFO: Looking for ctypes DLLs
4493 INFO: Analyzing run-time hooks ...
4501 INFO: Looking for dynamic libraries
4588 INFO: Looking for eggs
4588 INFO: Using Python library /Library/Frameworks/Python.framework/Versions/3.6/Python
4590 INFO: Warnings written to /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/warnReadCreditCardExcel.txt
4621 INFO: Graph cross-reference written to /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/xref-ReadCreditCardExcel.html
4638 INFO: checking PYZ
4638 INFO: Building PYZ because out00-PYZ.toc is non existent
4638 INFO: Building PYZ (ZlibArchive) /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/out00-PYZ.pyz
5023 INFO: Building PYZ (ZlibArchive) /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/out00-PYZ.pyz completed successfully.
5030 INFO: checking PKG
5030 INFO: Building PKG because out00-PKG.toc is non existent
5030 INFO: Building PKG (CArchive) out00-PKG.pkg
5038 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
5039 INFO: Bootloader /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyInstaller/bootloader/Darwin-64bit/run
5039 INFO: checking EXE
5039 INFO: Building EXE because out00-EXE.toc is non existent
5039 INFO: Building EXE from out00-EXE.toc
5039 INFO: Appending archive to EXE /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/ReadCreditCardExcel
5041 INFO: Fixing EXE for code signing /Users/hanruikai/eclipse-workspace/build/ReadCreditCardExcel/ReadCreditCardExcel
5043 INFO: Building EXE from out00-EXE.toc completed successfully.
5044 INFO: checking COLLECT
5044 INFO: Building COLLECT because out00-COLLECT.toc is non existent
5044 INFO: Building COLLECT out00-COLLECT.toc
5529 INFO: Building COLLECT out00-COLLECT.toc completed successfully.

生成的目录如下:

total 24
drwxr-xr-x   9 hanruikai  staff  306 Dec 21 11:44 nodejs
drwxr-xr-x   5 hanruikai  staff  170 Jan 25 17:17 Java
drwxr-xr-x   5 hanruikai  staff  170 Jan 25 17:21 Test
drwxr-xr-x  14 hanruikai  staff  476 Feb 24 11:25 puhui-newapp-all
drwxr-xr-x   2 hanruikai  staff   68 Mar  9 15:36 src
drwxr-xr-x   3 hanruikai  staff  102 Mar  9 15:36 resources
-rw-r--r--   1 hanruikai  staff  662 Mar  9 15:36 Mybatis-generator.iml
drwxr-xr-x   3 hanruikai  staff  102 Mar 19 10:24 mygithub
drwxr-xr-x  18 hanruikai  staff  612 Apr 12 11:35 flow-platform-aggregator
-rw-r--r--   1 hanruikai  staff  939 Apr 12 16:28 ReadCreditCardExcel.py
drwxr-xr-x   3 hanruikai  staff  102 Apr 12 16:36 build
-rw-r--r--   1 hanruikai  staff  891 Apr 12 16:36 ReadCreditCardExcel.spec
drwxr-xr-x   3 hanruikai  staff  102 Apr 12 16:37 dist

drwxr-xr-x   3 hanruikai  staff  102 Apr 12 16:37 __pycache__

进入dist目录:

hanruikaideMacBook-Pro:ReadCreditCardExcel hanruikai$ pwd
/Users/hanruikai/eclipse-workspace/dist/ReadCreditCardExcel

hanruikaideMacBook-Pro:ReadCreditCardExcel hanruikai$ ls
Python                  _codecs_cn.so           _codecs_tw.so           _lzma.so                _posixsubprocess.so     _sha3.so                array.so                libncursesw.5.dylib     readline.so             zlib.so
ReadCreditCardExcel     _codecs_hk.so           _datetime.so            _md5.so                 _random.so              _sha512.so              base_library.zip        libssl.1.0.0.dylib      resource.so
_bisect.so              _codecs_iso2022.so      _elementtree.so         _multibytecodec.so      _scproxy.so             _socket.so              binascii.so             math.so                 select.so
_blake2.so              _codecs_jp.so           _hashlib.so             _opcode.so              _sha1.so                _ssl.so                 grp.so                  mmap.so                 termios.so
_bz2.so                 _codecs_kr.so           _heapq.so               _pickle.so              _sha256.so              _struct.so              libcrypto.1.0.0.dylib   pyexpat.so              unicodedata.so

hanruikaideMacBook-Pro:ReadCreditCardExcel hanruikai$ ls  


执行上面红色名称的文件

hanruikaideMacBook-Pro:ReadCreditCardExcel hanruikai$ ReadCreditCardExcel 
工作表1 27 255
['光大福IC信用卡', 'https://xyk.cebbank.com/cebmms/apply/ps/card-index.htm?req_card_id=8351&pro_code=FHTG040000SJ142SZJD&c2c_recom_flag=', 'FHTG040000SJ150SZJD', '10元抢电影票、10元享美食', '首年免年费', '10元观影', '易下卡', '人民币单币种', '首年免,交易免', '金卡','', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
['编码', '列3', 'FHTG040000SJ150SZJD', 'FHTG040000SJ150SZJD', 'FHTG040000SJ150SZJD', 'FHTG040000SJ150SZJD', 'A1027165145157', '', 'knhd000044', '', '', 57.0, '', '', 'F1301043', '', 'N3700MM2061Q665700FS', 'N3700MM2061Q665700FS', '', '', '', 950000657.0, 950000657.0,0000657.0, 950000657.0, 950000657.0, 950000657.0]
b'\xe5\x88\x971'
b'\xe5\x88\x971'
b'\xe5\x88\x971'

1


大功告成!!!!


你可能感兴趣的:(Python,互联网技术栈)