Home Backend Development Python Tutorial python高手之路python处理excel文件(方法汇总)

python高手之路python处理excel文件(方法汇总)

Jun 10, 2016 pm 03:06 PM

用python来自动生成excel数据文件。python处理excel文件主要是第三方模块库xlrd、xlwt、xluntils和pyExcelerator,除此之外,python处理excel还可以用win32com和openpyxl模块。

方法一:

小罗问我怎么从excel中读取数据,然后我百了一番,做下记录

excel数据图(小罗说数据要给客户保密,我随手写了几行数据):

python读取excel文件代码:

1

2

3

4

5

6

7

8

9

10

11

12

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# 读取excel数据

# 小罗的需求,取第二行以下的数据,然后取每行前13列的数据

import xlrd

data = xlrd.open_workbook('test.xls') # 打开xls文件

table = data.sheets()[0] # 打开第一张表

nrows = table.nrows # 获取表的行数

for i in range(nrows): # 循环逐行打印

if i == 0: # 跳过第一行

continue

print table.row_values(i)[:13] # 取前十三列

Copy after login

excel的写操作等后面用到的时候在做记录

方法二:

使用xlrd读取文件,使用xlwt生成Excel文件(可以控制Excel中单元格的格式)。但是用xlrd读取excel是不能对其进行操作的;而xlwt生成excel文件是不能在已有的excel文件基础上进行修改的,如需要修改文件就要使用xluntils模块。pyExcelerator模块与xlwt类似,也可以用来生成excel文件。

1. [代码]test_xlrd.py

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

#coding=utf-8

#######################################################

#filename:test_xlrd.py

#author:defias

#date:xxxx-xx-xx

#function:读excel文件中的数据

#######################################################

import xlrd

#打开一个workbook

workbook = xlrd.open_workbook('E:\\Code\\Python\\testdata.xls')

#抓取所有sheet页的名称

worksheets = workbook.sheet_names()

print('worksheets is %s' %worksheets)

#定位到sheet1

worksheet1 = workbook.sheet_by_name(u'Sheet1')

"""

#通过索引顺序获取

worksheet1 = workbook.sheets()[0]

#或

worksheet1 = workbook.sheet_by_index(0)

"""

"""

#遍历所有sheet对象

for worksheet_name in worksheets:

worksheet = workbook.sheet_by_name(worksheet_name)

"""

#遍历sheet1中所有行row

num_rows = worksheet1.nrows

for curr_row in range(num_rows):

row = worksheet1.row_values(curr_row)

print('row%s is %s' %(curr_row,row))

#遍历sheet1中所有列col

num_cols = worksheet1.ncols

for curr_col in range(num_cols):

col = worksheet1.col_values(curr_col)

print('col%s is %s' %(curr_col,col))

#遍历sheet1中所有单元格cell

for rown in range(num_rows):

for coln in range(num_cols):

cell = worksheet1.cell_value(rown,coln)

print cell

"""

#其他写法:

cell = worksheet1.cell(rown,coln).value

print cell

#或

cell = worksheet1.row(rown)[coln].value

print cell

#或

cell = worksheet1.col(coln)[rown].value

print cell

#获取单元格中值的类型,类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

cell_type = worksheet1.cell_type(rown,coln)

print cell_type

"""

Copy after login

2. [代码]test_xlwt.py

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

#coding=utf-8

#######################################################

#filename:test_xlwt.py

#author:defias

#date:xxxx-xx-xx

#function:新建excel文件并写入数据

#######################################################

import xlwt

#创建workbook和sheet对象

workbook = xlwt.Workbook() #注意Workbook的开头W要大写

sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)

sheet2 = workbook.add_sheet('sheet2',cell_overwrite_ok=True)

#向sheet页中写入数据

sheet1.write(0,0,'this should overwrite1')

sheet1.write(0,1,'aaaaaaaaaaaa')

sheet2.write(0,0,'this should overwrite2')

sheet2.write(1,2,'bbbbbbbbbbbbb')

"""

#-----------使用样式-----------------------------------

#初始化样式

style = xlwt.XFStyle()

#为样式创建字体

font = xlwt.Font()

font.name = 'Times New Roman'

font.bold = True

#设置样式的字体

style.font = font

#使用样式

sheet.write(0,1,'some bold Times text',style)

"""

#保存该excel文件,有同名文件时直接覆盖

workbook.save('E:\\Code\\Python\\test2.xls')

print '创建excel文件完成!'

Copy after login

3. [代码]test_xlutils.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#coding=utf-8

#######################################################

#filename:test_xlutils.py

#author:defias

#date:xxxx-xx-xx

#function:向excel文件中写入数据

#######################################################

import xlrd

import xlutils.copy

#打开一个workbook

rb = xlrd.open_workbook('E:\\Code\\Python\\test1.xls')

wb = xlutils.copy.copy(rb)

#获取sheet对象,通过sheet_by_index()获取的sheet对象没有write()方法

ws = wb.get_sheet(0)

#写入数据

ws.write(1, 1, 'changed!')

#添加sheet页

wb.add_sheet('sheetnnn2',cell_overwrite_ok=True)

#利用保存时同名覆盖达到修改excel文件的目的,注意未被修改的内容保持不变

wb.save('E:\\Code\\Python\\test1.xls')

Copy after login

4. [代码]test_pyExcelerator_read.py

1

2

3

4

5

6

7

8

9

10

11

12

#coding=utf-8

#######################################################

#filename:test_pyExcelerator_read.py

#author:defias

#date:xxxx-xx-xx

#function:读excel文件中的数据

#######################################################

import pyExcelerator

#parse_xls返回一个列表,每项都是一个sheet页的数据。

#每项是一个二元组(表名,单元格数据)。其中单元格数据为一个字典,键值就是单元格的索引(i,j)。如果某个单元格无数据,那么就不存在这个值

sheets = pyExcelerator.parse_xls('E:\\Code\\Python\\testdata.xls')

print sheets

Copy after login

5. [代码]test_pyExcelerator.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

#coding=utf-8

#######################################################

#filename:test_pyExcelerator.py

#author:defias

#date:xxxx-xx-xx

#function:新建excel文件并写入数据

#######################################################

import pyExcelerator

#创建workbook和sheet对象

wb = pyExcelerator.Workbook()

ws = wb.add_sheet(u'第一页')

#设置样式

myfont = pyExcelerator.Font()

myfont.name = u'Times New Roman'

myfont.bold = True

mystyle = pyExcelerator.XFStyle()

mystyle.font = myfont

#写入数据,使用样式

ws.write(0,0,u'ni hao 帕索!',mystyle)

#保存该excel文件,有同名文件时直接覆盖

wb.save('E:\\Code\\Python\\mini.xls')

print '创建excel文件完成!'

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles