乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > 如何用<em>python</em>读取excel文件内容并写到另一个exce...-pytho

如何用<em>python</em>读取excel文件内容并写到另一个exce...-pytho

作者:乔山办公网日期:

返回目录:excel表格制作


python操作excel的类库可以用这个:e69da5e6ba907a64366

http:///python-excel/tutorial/blob/master/tests/test_examples.py

我摘抄一段吧,

import os

from cStringIO import StringIO
from glob import glob
from os import path, environ
from os.path import abspath
from re import compile
from shutil import copy
from subprocess import call, STDOUT
from tempfile import TemporaryFile
from testfixtures import TempDirectory, compare
from xlrd import Book, biff_dump

initial = os.getcwd()
base = abspath(path.join(path.dirname(abspath(__file__)), os.pardir))
runner = abspath(path.join(base, 'bin', 'py'))
examples = path.join(base, 'students')
expected = path.join(base, 'tests', 'expected')

sub_res = [
    (compile('0+x[0-9A-Fa-f]+'), '...'),
    (compile('".+'+os.sep.replace('\\','\\\\')+'(.+.py)"'), '"\\1"'),
    ]

def get_biff_records(data):
    outfile = StringIO()
    bk = Book()
    bk.biff2_8_load(file_contents=data, logfile=outfile, )
    biff_dump(bk.mem, bk.base, bk.stream_len, 0, outfile, unnumbered=True)
    return outfile.getvalue()
    
def check_example(package, filename):
    example_dir = path.join(examples, package)
    expected_dir = path.join(expected, package)
    expected_base = path.join(expected_dir, path.splitext(filename)[0])
        
    try:
        
        with TempDirectory() as actual:
            # copy files to the directory
            copy(path.join(example_dir, filename), actual.path)
            for pattern in ('*.xls', '*.bmp'):
                for fixture in glob(path.join(example_dir, pattern)):
                    copy(fixture, actual.path)

            os.chdir(actual.path)
            output = TemporaryFile('w+')

            # run the example
            before_listing = set(os.listdir(actual.path))
            call([runner, filename], stdout=output, stderr=STDOUT)
            after_listing = set(os.listdir(actual.path))

            # check the console output
            output.seek(0)
            actual_output = output.read().strip().replace('\r', '')
            for re, rp in sub_res:
                actual_output = re.sub(rp, actual_output)
            expected_path = expected_base+'.txt'
            if not path.exists(expected_path):
                expected_output = ''
            else:
                expected_output = open(expected_path).read().strip().replace('\r', '')
            compare(expected_output, actual_output)

            # check the files created
            created = after_listing.difference(before_listing)

            expected_names = set()
            if os.path.exists(expected_base):
                expected_names = set(os.listdir(expected_base))
                
            for name in created:
                with open(path.join(actual.path, name), 'rb') as af:
                    actual_data = af.read()

                if name in expected_names:
                    expected_path = path.join(expected_base, name)
                    expected_data = open(expected_path, 'rb').read()
                    expected_names.remove(name)
                    if actual_data != expected_data:
                        if environ.get('REPLACE_EXAMPLES'):
                            with open(expected_path, 'wb') as new_expected:
                                new_expected.write(actual_data)
                        compare(
                            get_biff_records(expected_data),
                            get_biff_records(actual_data),
                            )
                else:
                    raise AssertionError("unexpected output: %s" % name)
            
            for name in expected_names:
                if name != '.svn':
                    print created
                    raise AssertionError("expected output missing: %s" % name)
        
            
    finally:
        os.chdir(initial)
    
def test_examples():
    for package in ('xlrd', 'xlwt', 'xlutils'):
        for py in glob(path.join(examples, package, '*.py')):
            yield check_example, package, path.split(py)[1]


XlsxWriter-master
xlrd
用这两个模块,一个写,一个读,非常方便。
一、读excel表
读excel要用到xlrd模块,官网安装(http://pypi.python.org/pypi/xlrd)。然后就可以跟着里面的例子稍微试一下e799bee5baa6e78988e69d83337就知道怎么用了。大概的流程是这样的:
1、导入模块

复制代码代码如下:
import xlrd

2、打开Excel文件读取数据

复制代码代码如下:
data = xlrd.open_workbook('excel.xls')

3、获取一个工作表
① table = data.sheets()[0] #通过索引顺序获取
② table = data.sheet_by_index(0) #通过索引顺序获取
③ table = data.sheet_by_name(u'Sheet1')#通过名称获取
4、获取整行和整列的值(返回数组)

复制代码代码如下:
table.row_values(i)
table.col_values(i)

5、获取行数和列数 

复制代码代码如下:
table.nrows
table.ncols

6、获取单元格

复制代码代码如下:
table.cell(0,0).value
table.cell(2,3).value

就我自己使用的时候觉得还是获取cell最有用,这就相当于是给了你一个二维数组,余下你就可以想怎么干就怎么干了。得益于这个十分好用的库代码很是简洁。但是还是有若干坑的存在导致话了一定时间探索。现在列出来供后人参考吧:

1、首先就是我的统计是根据姓名统计各个表中的信息的,但是调试发现不同的表中各个名字貌似不能够匹配,开始怀疑过编码问题,不过后来发现是因为  空格。因为在excel中输入的时候很可能会顺手在一些名字后面加上几个空格或是tab键,这样看起来没什么差别,但是程序处理的时候这就是两个完全  不同的串了。我的解决方法是给每个获取的字符串都加上strip()处理一下。效果良好
2、还是字符串的匹配,在判断某个单元格中的字符串(中文)是否等于我所给出的的时候发现无法匹配,并且各种unicode也不太奏效,百度过一些解决  方案,但是都比较复杂或是没用。最后我采用了一个比较变通的方式:直接从excel中获取我想要的值再进行比较,效果是不错就是通用行不太好,个  呢不能问题还没解决。
二、写excel表
写excel表要用到xlwt模块,官网下载(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:
1、导入模块

复制代码代码如下:
import xlwt

2、创建workbook(其实就是excel,后来保存一下就行)

复制代码代码如下:
workbook = xlwt.Workbook(encoding = 'ascii')

3、创建表

复制代码代码如下:
worksheet = workbook.add_sheet('My Worksheet')

4、往单元格内写入内容

复制代码代码如下:
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')

5、保存

复制代码代码如下:
workbook.save('Excel_Workbook.xls')

由于我的需求比较简单,所以这上面没遇到什么问题,唯一的就是建议还是用ascii编码,不然可能会有一些诡异的现象。

当然xlwt功能远远不止这些,他甚至可以设置各种样式之类的。附上一点例子

复制代码代码如下:

Examples Generating Excel Documents Using Python's xlwt

Here are some simple examples using Python's xlwt library to dynamically generate Excel documents.
Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffi

你好,
1,方法一: 打开Excel,点击“编辑”-“Office剪切板”,即可在窗口右侧出现“剪切板”。
2,方法二 Excel中,选中一单元格,连续两次按复制(或剪切)的快捷键“Ctrl+c”(或“Ctrl+x)”亦可调出“剪切板”

相关阅读

  • <em>python</em>读取<em>excel</em>的指定内容

  • 乔山办公网excel表格制作
  • 用python读取excel中的一列数据步骤如下:1、首先打开dos命令窗,安装抄必须的两个库,命令是:pip3 install xlrd;Pip3 install xlwt。2、准备好excel。3、打开pycharm,新建一个excel.py的文件,首先
关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网