Book

class Book(fullname=None, update_links=None, read_only=None, format=None, password=None, write_res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None, editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load=None, impl=None, json=None, mode=None, engine=None)

bookオブジェクトは books コレクションのメンバーです:

>>> import xlwings as xw
>>> xw.books[0]
<Book [Book1]>

xw.Book を使えば、最も簡単にブックに接続できます: xw.Book は接続先のブックを開いているかどうかを全てのExcelインスタンスに対して確認し、もし複数のExcelインスタンスが接続先のブックを同時に開いていればエラーを返します。アクティブなExcelインスタンスのブックに接続するには、 xw.books を使います。また、特定のappを参照するには次のようにします:

>>> app = xw.App()  # or xw.apps[10559] (get the PIDs via xw.apps.keys())
>>> app.books['Book1']

xw.Book

xw.books

New book

xw.Book()

xw.books.add()

Unsaved book

xw.Book('Book1')

xw.books['Book1']

Book by (full)name

xw.Book(r'C:/path/to/file.xlsx')

xw.books.open(r'C:/path/to/file.xlsx')

Parameters

fullnamestr or path-like object, default None

既存のワークブックのフルパスまたは名前(xlsx、xlsm等を含む)、もしくは未保存のワークブックの名前。フルパス以外の場合、カレント ワーキング ディレクトリーからファイルを探します。

update_linksbool, default None

引数が省略された場合、リンクのアップデートについてのプロンプトが現れます。

read_onlybool, default False

Trueにすればワークブックを読み取り専用で開きます

formatstr

テキストファイルを開くときの区切り文字を指定します

passwordstr

ワークブックを開くときのパスワード

write_res_passwordstr

ワークブックに書き込むときのパスワード

ignore_read_only_recommendedbool, default False

True を設定すれば読み取り専用を推奨するメッセージを非表示にできます

originint

For text files only. Specifies where it originated. Use Platform constants.

delimiterstr

formatの引数が6の場合、区切り文字を指定します。

editablebool, default False

このオプションはレガシーなMicrosoft Excel 4.0アドイン専用です。

notifybool, default False

読み込み/書き込みモードで開けなかったファイルが、使えるようになった時にユーザーに通知します。

converterint

ファイルオープン時に最初に使用するコンバーターのインデックス

add_to_mrubool, default False

このワークブックを最近追加したワークブックのリストに追加します。

localbool, default False

True の場合、Excelの言語に反してファイルを保存します。そうでなければ、VBAの言語に反して保存します。macOSではサポートされていません。

corrupt_loadint, default xlNormalLoad

xlNormalLoad、xlRepairFile、xlExtractDataから選択します。macOSではサポートされていません。

jsondict

A JSON object as delivered by the MS Office Scripts or Google Apps Script xlwings module but in a deserialized form, i.e., as dictionary.

Added in version 0.26.0.

modestr, default None

Either "i" (interactive (default)) or "r" (read). In interactive mode, xlwings opens the workbook in Excel, i.e., Excel needs to be installed. In read mode, xlwings reads from the file directly, without requiring Excel to be installed. Read mode requires xlwings PRO.

Added in version 0.28.0.

activate(steal_focus=False)

ブックをアクティブにします。

Parameters

steal_focusbool, default False

Trueの場合、最も前面のウインドウにし、フォーカスをPythonからExcelに変更します。

property api

使用しているエンジンのネイティブ オブジェクト(pywin32 オブジェクトまたは appscript オブジェクト)を返します。

Added in version 0.9.0.

property app

ブックを開いているappオブジェクトを返します。

Added in version 0.9.0.

classmethod caller()

Pythonの関数がExcelから RunPython で呼び出されている場合に、呼び出し元のブックを参照します。Excelから呼び出されている関数の中に入れてください。例:

import xlwings as xw

 def my_macro():
    wb = xw.Book.caller()
    wb.sheets[0].range('A1').value = 1

Pythonやデバッグ時にそのようなコードを簡単に実行するには、xw.Book.set_mock_caller() を使用してください。

Added in version 0.3.0.

close()

保存せずにブックを閉じます。

Added in version 0.1.1.

property fullname

ディスク上のパスを含むオブジェクトの名前を文字列で返します。読み取り専用。

json()

Returns a JSON serializable object as expected by the MS Office Scripts or Google Apps Script xlwings module. Only available with book objects that have been instantiated via xw.Book(json=...).

Added in version 0.26.0.

macro(name)

Excel VBA内のSubまたはFunctionを実行します。

Arguments

name : Name of Sub or Function with or without module name, e.g., 'Module1.MyMacro' or 'MyMacro'

次のVBA関数は

Function MySum(x, y)
    MySum = x + y
End Function

このように使うことができます:

>>> import xlwings as xw
>>> wb = xw.books.active
>>> my_sum = wb.macro('MySum')
>>> my_sum(1, 2)
3

App.macro() を参照

Added in version 0.7.1.

property name

ブックの名前を文字列で返します。

property names

ブックに含まれる(シート固有のものを含む)すべての名前の定義を表すnamesコレクションを返します。

バージョン 0.9.0 で変更.

render_template(**data)

このメソッドはxlwings PRO でのみ使用できます。

Replaces all Jinja variables (e.g {{ myvar }}) in the book with the keyword argument of the same name.

Added in version 0.25.0.

Parameters

data: kwargs

All key/value pairs that are used in the template.

>>> import xlwings as xw
>>> book = xw.Book()
>>> book.sheets[0]['A1:A2'].value = '{{ myvar }}'
>>> book.render_template(myvar='test')
save(path=None, password=None)

Saves the Workbook. If a path is provided, this works like SaveAs() in Excel. If no path is specified and if the file hasn't been saved previously, it's saved in the current working directory with the current filename. Existing files are overwritten without prompting. To change the file type, provide the appropriate extension, e.g. to save myfile.xlsx in the xlsb format, provide myfile.xlsb as path.

Arguments

pathstr or path-like object, default None

Path where you want to save the Book.

passwordstr, default None

Protection password with max. 15 characters

Added in version 0.25.1.

>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.save()
>>> wb.save(r'C:\path\to\new_file_name.xlsx')

Added in version 0.3.1.

property selection

選択しているセルをRangeとして返します。

Added in version 0.9.0.

set_mock_caller()

コードがExcelから RunPython で呼び出されるのではなく、Pythonから呼び出されている場合に、Excelファイルを xw.Book.caller() として利用するために設定します。

# This code runs unchanged from Excel via RunPython and from Python directly
import os
import xlwings as xw

def my_macro():
    sht = xw.Book.caller().sheets[0]
    sht.range('A1').value = 'Hello xlwings!'

if __name__ == '__main__':
    xw.Book('file.xlsm').set_mock_caller()
    my_macro()

Added in version 0.3.1.

property sheet_names

Returns

sheet_namesList

List of sheet names in order of appearance.

Added in version 0.28.1.

property sheets

ブック内のすべてのsheetを表すsheetsコレクションを返します。

Added in version 0.9.0.

to_pdf(path=None, include=None, exclude=None, layout=None, exclude_start_string='#', show=False, quality='standard')

Excelワークブック全体またはシートの一部をPDFファイルにエクスポートします。非表示のシートを印刷するには、明示的に include 引数に含める必要があります。

Parameters

pathstr or path-like object, default None

PDFファイルのパスで、デフォルトはワークブックと同じ名前、ディレクトリーになります。保存されていないワークブックの場合は、代わりにカレント ワーキング ディレトリーになります。

includeint or str or list, default None

どのシートを含めるか: シート番号(Excelのように1から始まるもの)またはシート名あるいはそれらのリストで指定します。

excludeint or str or list, default None

どのシートを除くか: シート番号(Excelのように1から始まるもの)またはシート名あるいはそれらのリストで指定します。

layoutstr or path-like object, default None

This argument requires xlwings PRO.

Path to a PDF file on which the report will be printed. This is ideal for headers and footers as well as borderless printing of graphics/artwork. The PDF file either needs to have only 1 page (every report page uses the same layout) or otherwise needs the same amount of pages as the report (each report page is printed on the respective page in the layout PDF).

Added in version 0.24.3.

exclude_start_stringstr, default '#'

Sheet names that start with this character/string will not be printed.

Added in version 0.24.4.

showbool, default False

Once created, open the PDF file with the default application.

Added in version 0.24.6.

qualitystr, default 'standard'

Quality of the PDF file. Can either be 'standard' or 'minimum'.

Added in version 0.26.2.

>>> wb = xw.Book()
>>> wb.sheets[0]['A1'].value = 'PDF'
>>> wb.to_pdf()

xlwings.Sheet.to_pdf() を参考

Added in version 0.21.1.