您好,登錄后才能下訂單哦!
python中怎么利用openpyxl 新增sheet,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
任務背景:
某excel 文件中有 21個 結構相同的sheet 需要匯總
利用openpyxl得到sheet 列表
from openpyxl import load_workbookworkbook = load_workbook(filename = "xxxxdata.xlsx")sheet_list = workbook.sheetnames
得到了sheet 列表,再利用pandas,讀取每一個sheet 后追加到一起,
import pandas as pd xls = pd.ExcelFile('xxxxxdata.xlsx')df1 = pd.read_excel(xls, '6.1',header=1)sheet_list_left =[ '6.2', '6.3', '6.4', '6.5', '6.7', '6.8', '6.9', '6.10', '6.11', '6.12', '6.14', '6.15', '6.16', '6.18', '6.17', '6.19', '6.21']
for each_sheet in sheet_list_left: print(each_sheet) df_each = pd.read_excel(xls,each_sheet,header=1 ) df_each= df_each[['采購姓名', '上架產品數量', '銷售總金額', '連云港', '徐淮臨日鹽', '揚州']] df_each['日期'] = each_sheet df1 = df1.append(df_each)
將df1 在原文件新增sheet,不覆蓋原有的sheet
import openpyxl
import pandas as pd
writer = pd.ExcelWriter('xxxxdata.xlsx',engine='openpyxl')
book = openpyxl.load_workbook(writer.path)
writer.book = book
df1.to_excel(writer, "新sheet名",index=False)
writer.save()
關于在excel中新增sheet不覆蓋,stackflow還有更好的答案,測試成功
import pandas as pdfrom openpyxl import load_workbookdef append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None, truncate_sheet=False, **to_excel_kwargs): """ Append a DataFrame [df] to existing Excel file [filename] into [sheet_name] Sheet. If [filename] doesn't exist, then this function will create it. Parameters: filename : File path or existing ExcelWriter (Example: '/path/to/file.xlsx') df : dataframe to save to workbook sheet_name : Name of sheet which will contain DataFrame. (default: 'Sheet1') startrow : upper left cell row to dump data frame. Per default (startrow=None) calculate the last row in the existing DF and write to the next row... truncate_sheet : truncate (remove and recreate) [sheet_name] before writing DataFrame to Excel file to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()` [can be dictionary] Returns: None """ # from openpyxl import load_workbook # import pandas as pd # ignore [engine] parameter if it was passed if 'engine' in to_excel_kwargs: to_excel_kwargs.pop('engine') writer = pd.ExcelWriter(filename, engine='openpyxl') # Python 2.x: define [FileNotFoundError] exception if it doesn't exist try: FileNotFoundError except NameError: FileNotFoundError = IOError try: # try to open an existing workbook writer.book = load_workbook(filename) # get the last row in the existing Excel sheet # if it was not specified explicitly if startrow is None and sheet_name in writer.book.sheetnames: startrow = writer.book[sheet_name].max_row # truncate sheet if truncate_sheet and sheet_name in writer.book.sheetnames: # index of [sheet_name] sheet idx = writer.book.sheetnames.index(sheet_name) # remove [sheet_name] writer.book.remove(writer.book.worksheets[idx]) # create an empty sheet [sheet_name] using old index writer.book.create_sheet(sheet_name, idx) # copy existing sheets writer.sheets = {ws.title:ws for ws in writer.book.worksheets} except FileNotFoundError: # file does not exist yet, we will create it pass if startrow is None: startrow = 0 # write out the new sheet df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs) # save the workbook writer.save()# 原文鏈接:https://blog.csdn.net/sdaujz/article/details/102080900
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。