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去獲得對應(yīng)的sheet,拿到sheet變量后,就可以往sheet中,寫入新的數(shù)據(jù)
4、寫完新數(shù)據(jù)后,最終save保存
源碼例子:
import xlrdimport osfrom xlutils.copy import copyfrom xlwt import Styledef 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)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選