python操作excel

import xlrd
import xlwt
from xlutils.copy import copy

打开想要更改的excel文件

old_excel = xlrd.open_workbook(‘fileName.xls’, formatting_info=True)

将操作文件对象拷贝,变成可写的workbook对象

new_excel = copy(old_excel)

获得第一个sheet的对象

ws = new_excel.get_sheet(0)

写入数据

ws.write(0, 0, ‘第一行,第一列’)
ws.write(0, 1, ‘第一行,第二列’)
ws.write(0, 2, ‘第一行,第三列’)
ws.write(1, 0, ‘第二行,第一列’)
ws.write(1, 1, ‘第二行,第二列’)
ws.write(1, 2, ‘第二行,第三列’)

另存为excel文件,并将文件命名

new_excel.save(‘new_fileName.xls’)

!/usr/bin/python

coding=utf-8

==============================================================================

#

Filename: demo.py

Description: excel operat

Created: Tue Apr 25 17:10:33 CST 2017

Author: Yur

#

==============================================================================

import xlwt

创建一个workbook 设置编码

workbook = xlwt.Workbook(encoding = ‘utf-8’)

创建一个worksheet

worksheet = workbook.add_sheet(‘My Worksheet’)

写入excel

参数对应 行, 列, 值

worksheet.write(1,0, label = ‘this is test’)

保存

workbook.save(‘Excel_test.xls’)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
运行后 会在当前目录生成一个Excel_test.xls
官方例子:

运行这个例子的时候 报错

自己又写了一个:

!/usr/bin/python

coding=utf-8

==============================================================================

#

Filename: style.py

Description: style

Created: Thu Apr 27 15:07:53 CST 2017

Author: Yur

#

==============================================================================

import xlwt

workbook = xlwt.Workbook(encoding = ‘ascii’)
worksheet = workbook.add_sheet(‘My Worksheet’)
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = ‘Times New Roman’
font.bold = True # 黑体
font.underline = True # 下划线
font.italic = True # 斜体字
style.font = font # 设定样式
worksheet.write(0, 0, ‘Unformatted value’) # 不带样式的写入

worksheet.write(1, 0, ‘Formatted value’, style) # 带样式的写入

workbook.save(‘formatting.xls’) # 保存文件
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
效果:

设置单元格宽度:
import xlwt

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
worksheet.write(0, 0,’My Cell Contents’)

设置单元格宽度

worksheet.col(0).width = 3333
workbook.save(‘cell_width.xls’)
1
2
3
4
5
6
7
8
9
输入一个日期到单元格:
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
style = xlwt.XFStyle()
style.num_format_str = ‘M/D/YY’ # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save(‘Excel_Workbook.xls’)
1
2
3
4
5
6
7
8
向单元格添加一个公式:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula(‘A1*B1’)) # Should output “10” (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula(‘SUM(A1,B1)’)) # Should output “7” (A1[5] + A2[2])
workbook.save(‘Excel_Workbook.xls’)
1
2
3
4
5
6
7
8
向单元格添加一个超链接:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
worksheet.write(0, 0, xlwt.Formula(‘HYPERLINK(“http://www.google.com“;”Google”)’)) # Outputs the text “Google” linking to http://www.google.com
workbook.save(‘Excel_Workbook.xls’)
1
2
3
4
5
合并列和行:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
worksheet.write_merge(0, 0, 0, 3, ‘First Merge’) # Merges row 0’s columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, ‘Second Merge’, style) # Merges row 1 through 2’s columns 0 through 3.
workbook.save(‘Excel_Workbook.xls’)
1
2
3
4
5
6
7
8
9
10
设置单元格内容的对其方式:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, ‘Cell Contents’, style)
workbook.save(‘Excel_Workbook.xls’)
1
为单元格议添加边框:

Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.

import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED
DASHED虚线
NO_LINE没有
THIN实线

May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.

borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, ‘Cell Contents’, style)
workbook.save(‘Excel_Workbook.xls’)lwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet’)
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on…
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, ‘Cell Contents’, style)
workbook.save(‘Excel_Workbook.xls’)介绍
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

* coding:utf-8 *

—————————————————————————-

import modules

—————————————————————————-

import os
import xlrd
from datetime import date,datetime

打开Excel文件

workbook = xlrd.open_workbook(‘09-10.11-38-12-HTTP-GOOD-1-Lte1sDataStat_Charts.xlsx’)

输出Excel文件中所有sheet的名字

print workbook.sheet_names()

根据sheet索引或者名称获取sheet内容

Data_sheet = workbook.sheets()[0]
CdfData_sheet = workbook.sheet_by_index(1)
Charts_sheet = workbook.sheet_by_name(u’Charts’)

获取sheet名称、行数和列数

print Data_sheet.name, Data_sheet.nrows, Data_sheet.ncols,\
CdfData_sheet.name, CdfData_sheet.nrows, CdfData_sheet.ncols,\
Charts_sheet.name, Charts_sheet.nrows, Charts_sheet.ncols

获取整行和整列的值(列表)

rows = Data_sheet.row_values(0) #获取第一行内容
cols = Data_sheet.col_values(1) #获取第二列内容

print rows

print cols

获取单元格内容

cell_A1 = Data_sheet.cell(0,0).value
cell_C1 = Data_sheet.cell(0,2).value
cell_B1 = Data_sheet.row(0)[1].value
cell_D2 = Data_sheet.col(3)[1].value
print cell_A1, cell_B1, cell_C1, cell_D2

获取单元格内容的数据类型

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

print ‘cell(0,0)数据类型:’, Data_sheet.cell(0,0).ctype
print ‘cell(1,0)数据类型:’, Data_sheet.cell(1,0).ctype
print ‘cell(1,1)数据类型:’, Data_sheet.cell(1,1).ctype
print ‘cell(1,2)数据类型:’, Data_sheet.cell(1,2).ctype

获取单元格内容为日期的数据

date_value = xlrd.xldate_as_tuple(Data_sheet.cell_value(1,0),workbook.datemode)
print date_value
print ‘%d:%d:%d’ %(date_value[3:])

d = {‘11:25:59’:[1, 2, 3], ‘11:26:00’:[2, 3, 4], ‘11:26:01’:[3, 4, 5]}
print d[‘11:25:59’]
print d[‘11:26:00’]
print d[‘11:26:01’]

print d[‘11:25:59’][0]
print d[‘11:26:00’][0]
print d[‘11:26:01’][0]

你可能感兴趣的:(python操作excel)