web-dev-qa-db-ja.com

他のシートを削除せずに既存のExcelワークシートにシートを追加する

Excelファイルex.xlsにシートを追加しようとしていますが、追加するたびに、以前に作成したすべてのシートが削除されます。

他のシートを削除せずにこのExcelファイルにシートを追加するにはどうすればよいですか?

シートを作成するための私のコードは次のとおりです。

import xlwt
import xlrd

wb = Workbook()
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')
4
Nick M.

私はこれがあなたが望むことをする唯一の方法だと信じています:

import xlrd, xlwt
from xlutils.copy import copy as xl_copy

# open existing workbook
rb = xlrd.open_workbook('ex.xls', formatting_info=True)
# make a copy of it
wb = xl_copy(rb)
# add sheet to workbook with existing sheets
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')
6
bernie

以下は、「openpyxl」を使用してExcelブックに新しいシートを作成する方法です。

import openpyxl

wb=openpyxl.load_workbook("Example_Excel.xlsx")
wb.create_sheet("Sheet1")  

シートまたはワークブックがまだ存在しない場合は、これを回避するためにエラーが発生します

import openpyxl

wb=openpyxl.load_workbook("Example_Excel.xlsx")
try:
    wb["Sheet1"]
except:
    wb.create_sheet("Sheet1") 

以下は、使用方法に応じて、複数のページに情報を書き込む例です。

import openpyxl

work_book = 'Example_Excel.xlsx'
sheets = "Sheet1","Sheet2","Sheet3","Sheet4","Sheet5"

for current_sheet in sheets:
    wb=openpyxl.load_workbook(work_book)

    #if the sheet doesn't exist, create a new sheet
    try:
      wb[current_sheet]
    except:
      wb.create_sheet(current_sheet) 

    #wait for user to press "Enter" before starting on next sheet
    raw_input("Press Enter to continue...")

#The code for you wish repeated for each page
    #This example will print the sheet name to "B2" cell on that sheet
    cell ="B"+str(2)
    sheet=wb[current_sheet]
    sheet[cell].value= current_sheet
1
Travis Boop