關于python3中的追加寫入excel問題,這個問題坑了我幾小時,其實加一個參數即可。
因為之前有寫好的excel,想追加寫入,但是寫入后卻只有寫入后的單元格格式,之前寫的完全消失。
以下是我的代碼
這代碼可以用是我做的一個爬蟲維護項目:
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
|
def times(): User_Agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36' headers = { 'User-Agent' : User_Agent } search_url = 'https://www.cnss.com.cn/u/cms/www/indexJson/bdi_month.json?v=1577414941357' request = urllib.request.Request(search_url, headers = headers) response = urllib.request.urlopen(request) content = response.read().decode( 'utf-8' ) content = ''.join(content) # print(content) # index = re.findall('index":"(.*?)"', content) # 獲取指數 date = re.findall( 'date":"(.*?)"' , content) # 獲取時間 time = [] i = 0 start_date = date[ 0 ].replace( '.' , '年' ) start_date.replace( '.' , '月' ) end_date = date[ - 1 ].replace( '.' , '年' ) end_date.replace( '.' , '月' ) # print(index,date,start_date,end_date) for j in range ( int ( len (date) / 1 )): temp = date[i:i + 1 ] i + = 1 time.append(temp) hears = start_date + '日' + '——' + end_date + '日' + '嘻嘻嘻' title = [ '交易日期' , '干散貨指數(BDI)' , '海岬型指數(BCI)' , '巴拿馬型指數(BPI)' , '超靈便型船運價指數(BSI)' , '靈便型船指數(BHSI)' ] sheet1.write_merge( 0 , 0 + 0 , 0 , 0 + 5 , hears, style) for ti in range ( len (title)): sheet1.write( 1 , ti + 0 , title[ti], style) for x in range ( len (time)): for y in range ( len (time[x])): sheet1.write(x + 2 , 0 , time[x][y], style) f.save( '你想放的路徑.xls' ) |
上面的代碼還是可以繼續使用
標題xlwt的缺陷:
xlwt只能創建一個全新的excel文件,然后對這個文件進行寫入內容以及保存。但是大多數情況下我們希望的是讀入一個excel文件,然后進行修改或追加,這個時候就需要xlutils了。
xlutils的簡單使用:
接下來的部分就是關鍵所在了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
formatting_info = True 這個參數能保留原excel格式 def write_excel_xls_append(path, value,u): index = len (value) # 獲取需要寫入數據的行數 workbook = xlrd.open_workbook( './result/30波羅的海干散貨運價指數.xls' ,formatting_info = True ) # 打開工作簿 sheets = workbook.sheet_names() # 獲取工作簿中的所有表格 worksheet = workbook.sheet_by_name(sheets[ 0 ]) # 獲取工作簿中所有表格中的的第一個表格 rows_old = worksheet.ncols # 獲取表格中已存在的數據的行數 new_workbook = copy(workbook) # 將xlrd對象拷貝轉化為xlwt對象 styleS = xlwt.XFStyle() alignment = xlwt.Alignment() alignment.horz = xlwt.Alignment.HORZ_CENTER alignment.vert = xlwt.Alignment.VERT_CENTER styleS.alignment = alignment new_worksheet = new_workbook.get_sheet( 0 ) # 獲取轉化后工作簿中的第一個表格 for i in range ( 0 , index): for j in range ( 0 , len (value[i])): new_worksheet.write(i + 2 , u + 1 , value[i][j],styleS) # 追加寫入數據,注意是從i+rows_old行開始寫入 new_workbook.save(path) # 保存工作簿 |
然后你就會發現你的excel簡直完美~~~
總結
以上所述是小編給大家介紹的python3中關于excel追加寫入格式被覆蓋問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
原文鏈接:https://blog.csdn.net/pengshengege/article/details/103874231