python寫入已存在的excel數(shù)據(jù)實例
python可以使用xlrd讀excel,使用xlwt寫excel,但是如果要把數(shù)據(jù)寫入已存在的excel,需要另外一個庫xlutils配合使用.
大概思路:
1、用xlrd.open_workbook打開已有的xsl文件
注意添加參數(shù)formatting_info=True,得以保存之前數(shù)據(jù)的格式
2、然后用,from xlutils.copy import copy;,之后的copy去從打開的xlrd的Book變量中,拷貝出一份,成為新的xlwt的Workbook變量
3、然后對于xlwt的Workbook變量,就是正常的:
通過get_sheet去獲得對應的sheet,拿到sheet變量后,就可以往sheet中,寫入新的數(shù)據(jù)
4、寫完新數(shù)據(jù)后,最終save保存
源碼例子:
import xlrd import os from xlutils.copy import copy from xlwt import Style def writeExcel(row, col, str, styl=Style.default_style): rb = xlrd.open_workbook(file, formatting_info=True) wb = copy(rb) ws = wb.get_sheet(0) ws.write(row, col, str, styl) wb.save(file) style = xlwt.easyxf('font:height 240, color-index red, bold on;align: wrap on, vert centre, horiz center'); writeExcel(1, 1, 'hello world', style)
如果需要excel原格式,需要加參數(shù)
formatting_info=True
如果需要加excel樣式,傳入樣式字符串給xlwt.easyxf即可
合并單元格:
ws.write_merge(top_row, bottom_row, left_column, right_column, string)
以上這篇python寫入已存在的excel數(shù)據(jù)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在python image 中安裝中文字體的實現(xiàn)方法
今天小編大家分享一篇在python image 中安裝中文字體的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08安裝Keras,tensorflow,并實現(xiàn)將虛擬環(huán)境添加到jupyter?notebook
這篇文章主要介紹了安裝Keras,tensorflow,并實現(xiàn)將虛擬環(huán)境添加到jupyter?notebook,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03