背景

Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据。

折腾过程

1.找到了参考资料:

writing to existing workbook using xlwt

其实是没有直接实现:

打开已有的excel文件,然后在文件最后写入,添加新数据

的函数的。

只不过,可以利用:

Working with Excel Files in Python

中的库,组合实现。

2. writing to existing workbook using xlwt

给出了示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
rom xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
 
START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3
 
rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
 
for row_index in range(START_ROW, r_sheet.nrows):
    age_nov = r_sheet.cell(row_index, col_age_november).value
    if age_nov == 3:
        #If 3, then Combo I 3-4 year old  for both summer1 and fall1
        w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
        w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')
 
wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])

3. 刚又看到,有更简洁的代码:

1
2
3
4
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

4.现在打算去试试。

先去安装xlrd:

【记录】Python中安装xlrd模块

6.再去安装xlutils:

【记录】Python中安装可以读写excel的xls文件的xlutils模块(需依赖于xlrd和xlwt)

7.接着可以去写代码了。

8.先是:

【已解决】Python中使用xlutils.copy出错:AttributeError: ‘module’ object has no attribute ‘copy’

9.后是:

【已解决】Python中使用xlutils的copy出错:AttributeError: ‘str’ object has no attribute ‘datemode’

10.后来是用如下代码:

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
import xlwt;
import xlrd;
#import xlutils;
from xlutils.copy import copy;
 
#init xls file
#styleBlueBkg= xlwt.easyxf('pattern: pattern solid, fore_colour sky_blue;');
#styleBold   = xlwt.easyxf('font: bold on');
styleBoldRed   = xlwt.easyxf('font: color-index red, bold on');
headerStyle = styleBoldRed;
wb = xlwt.Workbook();
ws = wb.add_sheet(gConst['xls']['sheetName']);
ws.write(0, 0, "Header",        headerStyle);
ws.write(0, 1, "CatalogNumber", headerStyle);
ws.write(0, 2, "PartNumber",    headerStyle);
wb.save(gConst['xls']['fileName']);
 
 
#open existed xls file
#newWb = xlutils.copy(gConst['xls']['fileName']);
#newWb = copy(gConst['xls']['fileName']);
oldWb = xlrd.open_workbook(gConst['xls']['fileName']);
print oldWb; #<xlrd.book.Book object at 0x000000000315C940>
newWb = copy(oldWb);
print newWb; #<xlwt.Workbook.Workbook object at 0x000000000315F470>
newWs = newWb.get_sheet(0);
newWs.write(1, 0, "value1");
newWs.write(1, 1, "value2");
newWs.write(1, 2, "value3");
print "write new values ok";
newWb.save(gConst['xls']['fileName']);
print "save with same name ok";

实现了,打开,刚刚保存的,已经存在的xls文件,

然后写入新数据的目的。

但是有个缺点,

第一次保存时的,带格式(标题内容为红色粗体)的内容:

重新写入新数据,再保存时,却丢失了之前的格式(标题没了红色粗体了):

11.后来还是参考:

writing to existing workbook using xlwt

中的那个标准答案,在用xlrd.open_workbook时,添加对应的参数formatting_info=True,就可以保留原有格式了。

完整代码:

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
import xlwt;
import xlrd;
#import xlutils;
from xlutils.copy import copy;
 
#init xls file
#styleBlueBkg= xlwt.easyxf('pattern: pattern solid, fore_colour sky_blue;');
#styleBold   = xlwt.easyxf('font: bold on');
styleBoldRed   = xlwt.easyxf('font: color-index red, bold on');
headerStyle = styleBoldRed;
wb = xlwt.Workbook();
ws = wb.add_sheet(gConst['xls']['sheetName']);
ws.write(0, 0, "Header",        headerStyle);
ws.write(0, 1, "CatalogNumber", headerStyle);
ws.write(0, 2, "PartNumber",    headerStyle);
wb.save(gConst['xls']['fileName']);
 
 
#open existed xls file
#newWb = xlutils.copy(gConst['xls']['fileName']);
#newWb = copy(gConst['xls']['fileName']);
oldWb = xlrd.open_workbook(gConst['xls']['fileName'], formatting_info=True);
print oldWb; #<xlrd.book.Book object at 0x000000000315C940>
newWb = copy(oldWb);
print newWb; #<xlwt.Workbook.Workbook object at 0x000000000315F470>
newWs = newWb.get_sheet(0);
newWs.write(1, 0, "value1");
newWs.write(1, 1, "value2");
newWs.write(1, 2, "value3");
print "write new values ok";
newWb.save(gConst['xls']['fileName']);
print "save with same name ok";
1
  

最后重新写入的数据,就可以保留之前的格式了(标题为红色粗体):

总结

python中操作,本身就复杂的xls文件,还是有点小麻烦的。

想要,往已经存在的xls文件中,写入新的行,新的数据,对应的逻辑为:

  1. 用xlrd.open_workbook打开已有的xsl文件
    • 注意添加参数formatting_info=True,得以保存之前数据的格式
  2. 然后用,from xlutils.copy import copy;,之后的copy去从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量
  3. 然后对于xlwt的Workbook变量,就是正常的:
    1. 通过get_sheet去获得对应的sheet
    2. 拿到sheet变量后,就可以往sheet中,写入新的数据
  4. 写完新数据后,最终save保存

相关完整代码为:

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;
import xlrd;
#import xlutils;
from xlutils.copy import copy;
 
styleBoldRed   = xlwt.easyxf('font: color-index red, bold on');
headerStyle = styleBoldRed;
wb = xlwt.Workbook();
ws = wb.add_sheet(gConst['xls']['sheetName']);
ws.write(0, 0, "Header",        headerStyle);
ws.write(0, 1, "CatalogNumber", headerStyle);
ws.write(0, 2, "PartNumber",    headerStyle);
wb.save(gConst['xls']['fileName']);
 
#open existed xls file
#newWb = xlutils.copy(gConst['xls']['fileName']);
#newWb = copy(gConst['xls']['fileName']);
oldWb = xlrd.open_workbook(gConst['xls']['fileName'], formatting_info=True);
print oldWb; #<xlrd.book.Book object at 0x000000000315C940>
newWb = copy(oldWb);
print newWb; #<xlwt.Workbook.Workbook object at 0x000000000315F470>
newWs = newWb.get_sheet(0);
newWs.write(1, 0, "value1");
newWs.write(1, 1, "value2");
newWs.write(1, 2, "value3");
print "write new values ok";
newWb.save(gConst['xls']['fileName']);
print "save with same name ok";

其中,关于如何下载和安装对应的库,可参考:

【记录】Python中生成(写入数据到)Excel文件中

【记录】Python中安装xlrd模块

【记录】Python中安装可以读写excel的xls文件的xlutils模块(需依赖于xlrd和xlwt)

 

Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据的更多相关文章

  1. Python文件操作:文件的打开关闭读取写入

    Python文件操作:文件的打开关闭读取写入 一.文件的打开关闭 Python能以文本和二进制两种方式处理文件,本文主要讨论在Python3中文本文件的操作. 文件操作都分为以下几个步骤: 1.打开文 ...

  2. 以流方式读写文件:文件菜单打开一个文件,文件内容显示在RichTexBox中,执行复制、剪切、粘贴后,通过文件菜单可以保存修改后的文件。

    MainWindow.xaml文件 <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&q ...

  3. python中添加环境变量

    import sys sys.path 系统环境是一个list,可以将自己需要的库添加进入,例如mysql库,hive库等等.有三种方式添加,均验证通过:     1 临时添加,在一个shell窗口中 ...

  4. centos下python中添加easygui模块

    前提:python中要集成Tkinter,Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同 ...

  5. pyhon对excel的xls与xlsx的读取,写入

    import shutilimport osfrom openpyxl import load_workbookfrom xlutils.copy import copyimport win32com ...

  6. Python中添加中文注释报错SyntaxError: Non-UTF-8 code starting with '\xc1'

    问题:在文本编辑器中编辑Python文件时添加中文注释,运行python文件时报错.SyntaxError: Non-UTF-8 code starting with '\xc1' 解决方法:在文本开 ...

  7. python中添加日志记录到文件

    1.实现python日志功能 2.只输出到文件,不输出到控制台 #encoding:utf-8 import logging from common import path_util logging_ ...

  8. python中添加requests资源包

    1.进入资源网址下载:https://www.lfd.uci.edu/~gohlke/pythonlibs/ 2.按下CTRL+F进行页面查找“requests” 3.点击requests-2.22. ...

  9. Python中模块json与pickle的功能介绍

    json & pickle & shelve 1. json的序列化与反序列化 json的使用需要导入该模块,一般使用import json即可. json的序列化 方法1:json. ...

  10. LeNet - Python中的卷积神经网络

    本教程将  主要面向代码,  旨在帮助您 深入学习和卷积神经网络.由于这个意图,我  不会花很多时间讨论激活功能,池层或密集/完全连接的层 - 将来会有  很多教程在PyImageSearch博客上将 ...

随机推荐

  1. LRU Cache [LeetCode]

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  2. 并发编程 19—— 显式的Conditon 对象

    Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...

  3. iOS基础篇(十三)——UITableView(一)重用机制

    UITableView是app开发中常用到的控件,功能很强大,常用于数据的显示.在学习UITableView使用之前,我们先简单了解一下: 1.UITableView的重用机制 UITableView ...

  4. css知识点积累

    关于样式的优先级问题: !important > style > [ id > class > tag ];  z-index 的属性用法: z-index属性是用来设置元素的 ...

  5. varchar类型转换为numeric的值时有问题原因

    numeric的值不应该用单引号括起来...........

  6. c#网络通信框架networkcomms内核解析之九 自定义处理方法的运行机制

    NetworkComms网络通信框架序言 本文基于networkcomms2.3.1开源版本  gplv3协议 我们自己写的处理方法都称之为自定义处理方法 比如,我们在服务器上写的与登陆相关的处理方法 ...

  7. iOS开发UI篇—在UITableview的应用中使用动态单元格来完成app应用程序管理界面的搭建

    iOS开发UI篇—在UITableview的应用中使用动态单元格来完成app应用程序管理界面的搭建 一.实现效果 说明:该示例在storyboard中使用动态单元格来完成. 二.实现 1.项目文件结构 ...

  8. sql Sever的存储过程转换为mysql的

    总体来说,sql sever和Mysql的存储过程的思路都是一样的,但是在语法和结构上还是有很大的区别的.1. 在mysql中写存储过程所有的dbo都要去掉.2. 每一个sql语句后面都需要加上:否则 ...

  9. build.xml详解

    build.xml详解1.<project>标签每个构建文件对应一个项目.<project>标签时构建文件的根标签.它可以有多个内在属性,就如代码中所示,其各个属性的含义分别如 ...

  10. Visual Studio 拓展插件——Image Optimizer

    一句话概括效用:在Visual Studio的解决方案中,为图片或包含图片的文件夹添加右键菜单,可对图片进行压缩,无损压缩. 在VS扩展工具中安装 安装好后在VS资源管理器中选择图片右键,在右键菜单中 ...