Python API¶
顶层函数¶
- xlwings.load(index=1, header=1, chunksize=5000)¶
Loads the selected cell(s) of the active workbook into a pandas DataFrame. If you select a single cell that has adjacent cells, the range is auto-expanded (via current region) and turned into a pandas DataFrame. If you don’t have pandas installed, it returns the values as nested lists.
注解
Only use this in an interactive context like e.g. a Jupyter notebook! Don’t use this in a script as it depends on the active book.
- 参数
index (bool or int, default 1) – Defines the number of columns on the left that will be turned into the DataFrame’s index
header (bool or int, default 1) – Defines the number of rows at the top that will be turned into the DataFrame’s columns
chunksize (int, default 5000) – Chunks the loading of big arrays.
示例
>>> import xlwings as xw >>> xw.load()
See also:
view
在 0.23.1 版更改.
- xlwings.view(obj, sheet=None, table=True, chunksize=5000)¶
缺省情况下会创建一个新的工作簿并在第一个工作表上显示一个对象。如果提供了一个工作表对象,在显示对象之前会清除工作表里面的内容。
注解
Only use this in an interactive context like e.g. a Jupyter notebook! Don’t use this in a script as it depends on the active book.
- 参数
obj (any type with built-in converter) – 要显示的对象,比如:数字、字符串、numpy arrays、 pandas dataframes
sheet (Sheet, default None) – 工作表对象。如果没有提供这个参数,会使用一个新建工作簿的第一个工作表。
table (bool, default True) – If your object is a pandas DataFrame, by default it is formatted as an Excel Table
chunksize (int, default 5000) – Chunks the loading of big arrays.
示例
>>> import xlwings as xw >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) >>> xw.view(df)
See also:
load
在 0.22.0 版更改.
对象模型¶
Apps¶
App¶
- class xlwings.App(visible=None, spec=None, add_book=True, impl=None)¶
An app corresponds to an Excel instance and should normally be used as context manager to make sure that everything is properly cleaned up again and to prevent zombie processes. New Excel instances can be fired up like so:
import xlwings as xw with xw.App() as app: print(app.books)
一个app对象是apps集合中的一员:
>>> xw.apps Apps([<Excel App 1668>, <Excel App 1644>]) >>> xw.apps[1668] # get the available PIDs via xw.apps.keys() <Excel App 1668> >>> xw.apps.active <Excel App 1668>
- 参数
visible (bool, default None) – 返回或设置一个决定app是否可见的布尔值。缺省情况下保持状态不变,或者对象还不存在的情况下设置visible=True。
spec (str, default None) – 仅用于Mac系统, 使用Excel程序的全路径,例如:
/Applications/Microsoft Office 2011/Microsoft Excel
或/Applications/Microsoft Excel``在Windows系统中, 如果想改变xlwings调用的Excel版本,到 ``控制面板 > 程序和功能
把Office修复
到需要用的那个版本。
注解
在Mac系统里, 虽然xlwings允许多个Excel同时运行,但这不是Mac版的Excel官方支持的功能:不像在Windows系统里,当文件已经在另外一个Excel实例中打开的时候,不会要求你打开一个只读版本。就是说你得自己小心注意,避免同样的文件被不同的Excel实例重写。
- activate(steal_focus=False)¶
激活让一个Excel应用程序
- 参数
steal_focus (bool, default False) – 如果为True, 让Excel程序变为最前台的应用,并且把焦点从Python切换到Excel。
0.9.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- property books¶
当前打开的所有工作簿对象的集合。
0.9.0 新版功能.
- calculate()¶
把所以打开的工作簿中的公式重新计算一遍。
0.3.6 新版功能.
- property calculation¶
返回或设置calculation的值,这个值表示了工作簿的计算模式,有:
'manual'(手动)
,'automatic'(自动)
,'semiautomatic'(半自动)
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> wb.app.calculation = 'manual'
在 0.9.0 版更改.
- property cut_copy_mode¶
Gets or sets the status of the cut or copy mode. Accepts
False
for setting and returnsNone
,copy
orcut
when getting the status.0.24.0 新版功能.
- property display_alerts¶
缺省值为True。通过设置为False可以关闭正在运行的代码的报警信息;如果报警信息是需要响应的,Excel会选择默认的响应方式。
0.9.0 新版功能.
- property enable_events¶
True
if events are enabled. Read/write boolean.0.24.4 新版功能.
- property hwnd¶
返回Window句柄(仅用于Windows)。
0.9.0 新版功能.
- property interactive¶
True
if Excel is in interactive mode. If you set this property toFalse
, Excel blocks all input from the keyboard and mouse (except input to dialog boxes that are displayed by your code). Read/write Boolean. Note: Not supported on macOS.0.24.4 新版功能.
- kill()¶
通过杀掉进程强制Excel app退出。
0.9.0 新版功能.
- macro(name)¶
运行一个不属于特定工作簿但是属于加载项的Excel VBA的过程(sub)或函数。
- 参数
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 >>> app = xw.App() >>> my_sum = app.macro('MySum') >>> my_sum(1, 2) 3
Types are supported too:
>>> import xlwings as xw >>> app = xw.App() >>> my_sum = app.macro('MySum') >>> my_sum(1, 2) 3
However typed arrays are not supported. So the following won’t work
- Function MySum(arr() as integer)
‘’’ code here
End Function
参考:
Book.macro()
0.9.0 新版功能.
- property pid¶
返回app的PID。
0.9.0 新版功能.
- properties(**kwargs)¶
Context manager that allows you to easily change the app’s properties temporarily. Once the code leaves the with block, the properties are changed back to their previous state. Note: Must be used as context manager or else will have no effect. Also, you can only use app properties that you can both read and write.
示例
import xlwings as xw app = App() # Sets app.display_alerts = False with app.properties(display_alerts=False): # do stuff # Sets app.calculation = 'manual' and app.enable_events = True with app.properties(calculation='manual', enable_events=True): # do stuff # Makes sure the status bar is reset even if an error happens in the with block with app.properties(status_bar='Calculating...'): # do stuff
0.24.4 新版功能.
- quit()¶
退出应用,不保存任何工作簿。
0.3.3 新版功能.
- render_template(template=None, output=None, book_settings=None, **data)¶
This function requires xlwings PRO.
This is a convenience wrapper around
mysheet.render_template
Writes the values of all key word arguments to the
output
file according to thetemplate
and the variables contained in there (Jinja variable syntax). Following variable types are supported:strings, numbers, lists, simple dicts, NumPy arrays, Pandas DataFrames, pictures and Matplotlib/Plotly figures.
- 参数
template (str or path-like object) – Path to your Excel template, e.g.
r'C:\Path\to\my_template.xlsx'
output (str or path-like object) – Path to your Report, e.g.
r'C:\Path\to\my_report.xlsx'
book_settings (dict, default None) – A dictionary of
xlwings.Book
parameters, for details see:xlwings.Book
. For example:book_settings={'update_links': False}
.data (kwargs) – All key/value pairs that are used in the template.
- 返回
wb (xlwings Book)
.. versionadded:: 0.24.4
- property screen_updating¶
关掉屏幕刷新(设置为
False
)来加速脚本运行。虽然看不到脚本的运行情况,但是会让它运行更快。脚本运行完毕之后,记住把screen_updating属性值改回True
。0.3.3 新版功能.
- property selection¶
把选中的单元格作为区域返回。
0.9.0 新版功能.
- property startup_path¶
Returns the path to
XLSTART
which is where the xlwings add-in gets copied to by doingxlwings addin install
.0.19.4 新版功能.
- property status_bar¶
Gets or sets the value of the status bar. Returns
False
if Excel has control of it.0.20.0 新版功能.
- property version¶
返回Excel版本号对象。
示例
>>> import xlwings as xw >>> xw.App().version VersionNumber('15.24') >>> xw.apps[10559].version.major 15
在 0.9.0 版更改.
- property visible¶
取得或者设置Excel的visible属性值,可以为
True
或False
。0.3.3 新版功能.
Books¶
- class xlwings.main.Books(impl)¶
是
工作簿对象
的集合:>>> import xlwings as xw >>> xw.books # active app Books([<Book [Book1]>, <Book [Book2]>]) >>> xw.apps[10559].books # specific app, get the PIDs via xw.apps.keys() Books([<Book [Book1]>, <Book [Book2]>])
0.9.0 新版功能.
- property active¶
返回活动工作簿。
- add()¶
创建一个新的工作簿。新工作簿变成活动工作簿。返回一个工作簿对象。
- open(fullname, 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)¶
如果一个工作簿尚未打开,就打开并返回该工作簿。如果该工作簿已经打开了,不会触发异常,只是简单地返回该工作簿对象。
- 参数
fullname (str or path-like object) – 文件名或全路径文件名,例如
r'C:\path\to\file.xlsx'
或'file.xlsm'
。如果不是全路径,会在当前工作目录下寻找该文件。Parameters (Other) – 参考:
xlwings.Book()
- 返回
Book
- 返回类型
Book that has been opened.
Book¶
- class xlwings.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)¶
一个book对象是books集合中的一个成员:
>>> import xlwings as xw >>> xw.books[0] <Book [Book1]>
连接工作簿的最容易方法是由
xw.Book
提供的: 它在所有的app实例中查找需要的book对象。如果碰到同样的book在多个实例中被打开就返回一个错误。连接到活动app实例中的一个工作簿对象用xw.books
如果要特别指定具体的app, 可以用下列方法:>>> app = xw.App() # or something like xw.apps[10559] for existing apps, get the PIDs via xw.apps.keys() >>> app.books['Book1']
xw.Book
xw.books
新建工作簿
xw.Book()
xw.books.add()
未保存的工作簿
xw.Book('Book1')
xw.books['Book1']
带有全路径名的工作簿
xw.Book(r'C:/path/to/file.xlsx')
xw.books.open(r'C:/path/to/file.xlsx')
- 参数
fullname (str or path-like object, default None) – 已经存在的工作簿的文件名或全路径名(包括后缀
xlsx
,xlsm
等)或者还未保存的工作簿的名字。没有全路径时,在当前工作目录中寻找该文件。update_links (bool, default None) – 如果这个参数被省略,会提示用户确定更新链接的方式。
read_only (bool, default False) – 值为
True
时以只读方式打开工作簿format (str) – 如果打开的是文本文件,本参数指明分隔符。
password (str) – 用于打开工作簿的密码。
write_res_password (str) – 用于向工作簿写入数据时的密码。
ignore_read_only_recommended (bool, default False) – 设置为
True
时会关闭推荐只读的提示origin (int) – 仅用于文本文件,指定生成文本文件的系统平台。用的是XlPlatform枚举类型。[译者注:1对应Mac系统,2对应Windows系统,3对应Dos系统]
delimiter (str) – 如果参数format的值是6,这个参数指明分隔符。
editable (bool, default False) – 这个选择只用于老的Excel4.0的加载项。
notify (bool, default False) – 当一个文件暂时无法在读写模式中打开,在文件可以打开的时候提示用户。
converter (int) – 打开文件时,首先尝试使用的文件转换器对应的索引
add_to_mru (bool, default False) – 把这个工作簿加到最近增加的工作簿列表中。
local (bool, default False) – If
True
, saves files against the language of Excel, otherwise against the language of VBA. Not supported on macOS.corrupt_load (int, default xlNormalLoad) – 可以是xlNormalLoad、xlRepairFile或xlExtractData中的一个,在macOS上不支持此参数。
- activate(steal_focus=False)¶
激活工作簿
- 参数
steal_focus (bool, default False) – 如果是True, 把窗口显示到最上层,并且把焦点从Python切换到Excel。
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- property app¶
返回创建工作簿的app对象。
0.9.0 新版功能.
- classmethod caller()¶
References the calling book when the Python function is called from Excel via
RunPython
. Pack it into the function being called from Excel, e.g.:import xlwings as xw def my_macro(): wb = xw.Book.caller() wb.sheets[0].range('A1').value = 1
为了能够从Python中唤醒以便调试, 可以使用
xw.Book.set_mock_caller()
。0.3.0 新版功能.
- close()¶
放弃保存直接关闭工作簿。
0.1.1 新版功能.
- property fullname¶
返回对象名称字符串,包括在磁盘上的路径。是只读字符串。
- macro(name)¶
在Excel VBA中运行一个过程或者函数。
- 参数
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()
0.7.1 新版功能.
- property name¶
返回工作簿名称字符串。
- property names¶
返回一个指定工作簿中的定义过的所有命名区域的集合,包括那些和特定工作表有关的命名区域。
在 0.9.0 版更改.
- render_template(**data)¶
This method requires xlwings PRO.
Replaces all Jinja variables (e.g
{{ myvar }}
) in the book with the keyword argument that has the same name.0.25.0 新版功能.
- 参数
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)¶
保存工作簿。如果提供了路径,就类似于Excel中的SaveAs()。如果文件事先没有被保存过,有没有提供保存路径,会以当前的文件名保存在当前的工作目录中。同名文件会在没有提示的情况下被直接覆盖。
- 参数
path (str or path-like object, default None) – 工作簿的全路径名。
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> wb.save() >>> wb.save(r'C:\path\to\new_file_name.xlsx')
0.3.1 新版功能.
- property selection¶
把选中的单元格作为区域返回。
0.9.0 新版功能.
- set_mock_caller()¶
当源代码是直接从Pyhton调用而不是从Excel中通过RunPyton调用的时候,设置一个文件,模仿从这个文件中用
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()
0.3.1 新版功能.
- property sheets¶
返回工作簿中所有工作表的集合。
0.9.0 新版功能.
- to_pdf(path=None, include=None, exclude=None, layout=None, exclude_start_string='#', show=False)¶
Exports the whole Excel workbook or a subset of the sheets to a PDF file. If you want to print hidden sheets, you will need to list them explicitely under
include
.- 参数
path (str or path-like object, default None) – Path to the PDF file, defaults to the same name as the workbook, in the same directory. For unsaved workbooks, it defaults to the current working directory instead.
include (int or str or list, default None) – Which sheets to include: provide a selection of sheets in the form of sheet indices (1-based like in Excel) or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
exclude (int or str or list, default None) – Which sheets to exclude: provide a selection of sheets in the form of sheet indices (1-based like in Excel) or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
layout (str 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).
0.24.3 新版功能.
exclude_start_string (str, default '#') –
Sheet names that start with this character/string will not be printed.
0.24.4 新版功能.
show (bool, default False) –
Once created, open the PDF file with the default application.
0.24.6 新版功能.
示例
>>> wb = xw.Book() >>> wb.sheets[0]['A1'].value = 'PDF' >>> wb.to_pdf()
See also
xlwings.Sheet.to_pdf()
0.21.1 新版功能.
PageSetup¶
- class xlwings.main.PageSetup(impl)¶
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.24.2 新版功能.
- property print_area¶
Gets or sets the range address that defines the print area.
示例
>>> mysheet.page_setup.print_area = '$A$1:$B$3' >>> mysheet.page_setup.print_area '$A$1:$B$3' >>> mysheet.page_setup.print_area = None # clear the print_area
0.24.2 新版功能.
Sheets¶
- class xlwings.main.Sheets(impl)¶
全部工作表对象
sheet
的集合:>>> import xlwings as xw >>> xw.sheets # active book Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>]) >>> xw.Book('Book1').sheets # specific book Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
0.9.0 新版功能.
- property active¶
返回活动的工作表(Sheet)。
Sheet¶
- class xlwings.Sheet(sheet=None, impl=None)¶
一个sheet对象是sheets集合中的一员:
>>> import xlwings as xw >>> wb = xw.Book() >>> wb.sheets[0] <Sheet [Book1]Sheet1> >>> wb.sheets['Sheet1'] <Sheet [Book1]Sheet1> >>> wb.sheets.add() <Sheet [Book1]Sheet2>
在 0.9.0 版更改.
- activate()¶
激活sheet并把它返回。
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- autofit(axis=None)¶
在整个工作表中对行、列或者两者同时根据内容进行自适应。
- 参数
axis (string, default None) –
要做行自适应,用
rows
或r
要做列自适应,用
columns
或c
同时做行和列的自适应,不需要参数。
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> wb.sheets['Sheet1'].autofit('c') >>> wb.sheets['Sheet1'].autofit('r') >>> wb.sheets['Sheet1'].autofit()
0.2.3 新版功能.
- property book¶
返回指定工作表所属的工作簿。只读。
- property cells¶
返回一个代表工作表上所有单元格的区域对象(不仅仅是那些正在使用中的单元格)。
0.9.0 新版功能.
- clear()¶
重新格式化工作表,清除所有内容及格式。
- clear_contents()¶
清除工作表的所有内容但是保留原有格式。
- copy(before=None, after=None, name=None)¶
Copy a sheet to the current or a new Book. By default, it places the copied sheet after all existing sheets in the current Book. Returns the copied sheet.
0.22.0 新版功能.
- 参数
before (sheet object, default None) – The sheet object before which you want to place the sheet
after (sheet object, default None) – The sheet object after which you want to place the sheet, by default it is placed after all existing sheets
name (str, default None) – The sheet name of the copy
- 返回
Sheet object – The copied sheet
- 返回类型
示例
# Create two books and add a value to the first sheet of the first book first_book = xw.Book() second_book = xw.Book() first_book.sheets[0]['A1'].value = 'some value' # Copy to same Book with the default location and name first_book.sheets[0].copy() # Copy to same Book with custom sheet name first_book.sheets[0].copy(name='copied') # Copy to second Book requires to use before or after first_book.sheets[0].copy(after=second_book.sheets[0])
- delete()¶
删除工作表。
- property index¶
返回工作表的索引值(按照Excel的方式,从1开始的)。
- property name¶
取得或者设置工作表的名字。
- property names¶
返回所有名字与本工作表有关的命名区域的集合(名字定义中包含”SheetName!” (工作表名!)前缀)。
0.9.0 新版功能.
- property page_setup¶
Returns a PageSetup object.
0.24.2 新版功能.
- render_template(**data)¶
This method requires xlwings PRO.
Replaces all Jinja variables (e.g
{{ myvar }}
) in the sheet with the keyword argument that has the same name. Following variable types are supported:strings, numbers, lists, simple dicts, NumPy arrays, Pandas DataFrames, PIL Image objects that have a filename and Matplotlib figures.
0.22.0 新版功能.
- 参数
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.sheets[0].render_template(myvar='test')
- select()¶
选定工作表。只能在活动工作簿中选择。
0.9.0 新版功能.
- to_pdf(path=None, layout=None, show=False)¶
Exports the sheet to a PDF file.
- 参数
path (str or path-like object, default None) – Path to the PDF file, defaults to the name of the sheet in the same directory of the workbook. For unsaved workbooks, it defaults to the current working directory instead.
layout (str 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).
0.24.3 新版功能.
show (bool, default False) –
Once created, open the PDF file with the default application.
0.24.6 新版功能.
示例
>>> wb = xw.Book() >>> sheet = wb.sheets[0] >>> sheet['A1'].value = 'PDF' >>> sheet.to_pdf()
See also
xlwings.Book.to_pdf()
0.22.3 新版功能.
- property used_range¶
工作表中用过的区域。
- 返回
- 返回类型
xw.Range
0.13.0 新版功能.
- property visible¶
Gets or sets the visibility of the Sheet (bool).
0.21.1 新版功能.
Range¶
- class xlwings.Range(cell1=None, cell2=None, **options)¶
返回一个区域对象,可以代表一个单元格,也可以是一个区域。
- 参数
示例
活动工作表:
import xlwings as xw xw.Range('A1') xw.Range('A1:C3') xw.Range((1,1)) xw.Range((1,1), (3,3)) xw.Range('NamedRange') xw.Range(xw.Range('A1'), xw.Range('B2'))
指定的工作表:
xw.books['MyBook.xlsx'].sheets[0].range('A1')
- add_hyperlink(address, text_to_display=None, screen_tip=None)¶
在指定的区域(单个单元格)中加一个超链接
- 参数
address (str) – 超链接地址。
text_to_display (str, default None) – 超链接的显示字符串,缺省为超链接地址本身。
screen_tip (str, default None) – 当鼠标停留在超链接上方是显示的屏幕提示。缺省情况下设置为’<address> - 单击一次可跟踪超链接,单击并按住不放选择此单元格。’
0.3.0 新版功能.
- property address¶
返回一个表示区域引用的字符串,用
get_address()
可以使用参数来指定更多的细节。0.9.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- autofit()¶
使得区域内所有单元格的宽度和高度进行自适应。
只进行宽度自适应,用
xw.Range('A1:B2').columns.autofit()
只进行高度自适应时,使用
xw.Range('A1:B2').rows.autofit()
在 0.9.0 版更改.
- clear()¶
清除区域的内容和格式。
- clear_contents()¶
清除区域的内容,保留格式。
- property color¶
获取指定区域的背景色。
To set the color, either use an RGB tuple
(0, 0, 0)
or a hex string like#efefef
or an Excel color constant. To remove the background, set the color toNone
, see Examples.- 返回
RGB
- 返回类型
tuple
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range('A1').color = (255, 255, 255) # or '#ffffff' >>> xw.Range('A2').color (255, 255, 255) >>> xw.Range('A2').color = None >>> xw.Range('A2').color is None True
0.3.0 新版功能.
- property column¶
返回指定区域的第一列的值,只读。
- 返回
- 返回类型
Integer
0.3.5 新版功能.
- property column_width¶
获取或者设置区域的宽度(单位是字符数)。
Normal
风格中一个列宽单位就是一个字符宽度。 对于等宽字体,用的单位宽度是字符0(数字0)的宽度。如果区域中的列宽相同,返回宽度。如果各个列宽不同,返回
None
。列宽必须在下列范围内: 0 <= 列宽 <= 255
注意: 如果区域不在工作表已经使用的区域内,并且区域内的各列的宽度不同,返回第一列的宽度。
- 返回
- 返回类型
float
0.4.0 新版功能.
- property columns¶
返回一个
RangeColumns
对象,它代表指定区域内的列。0.9.0 新版功能.
- copy(destination=None)¶
把一个区域拷贝到目的区域或者剪贴板。
- 参数
destination (xlwings.Range) – 指定区域将被拷贝到的目的区域(xlwings Range对象)。如果省略,指定区域会被拷贝到剪贴板上。
- 返回
- 返回类型
None
- copy_picture(appearance='screen', format='picture')¶
Copies the range to the clipboard as picture.
- 参数
appearance (str, default 'screen') – Either ‘screen’ or ‘printer’.
format (str, default 'picture') – Either ‘picture’ or ‘bitmap’.
versionadded: (.) – 0.24.8:
- property count¶
返回单元格数量。
- property current_region¶
返回一个区域,这个区域由空行、空列或者工作表的边界围成的(不包含围绕区域的空行或空列)。这个和Windows中的
Ctrl-*
及Mac上的shift-Ctrl-Space
一致。- 返回
- 返回类型
Range object
- delete(shift=None)¶
删除一个单元格或者一个区域的单元格。
- 参数
shift (str, default None) – 使用
left
或up
。如果省略,Excel根据区域的形状决定。- 返回
- 返回类型
None
- end(direction)¶
返回区域内的边界单元格,得到的结果与按
Ctrl+Up
,Ctrl+down
,Ctrl+left
, 或Ctrl+right
组合键得到的结果相同。- 参数
direction (One of 'up', 'down', 'right', 'left') –
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range('A1:B2').value = 1 >>> xw.Range('A1').end('down') <Range [Book1]Sheet1!$A$2> >>> xw.Range('B2').end('right') <Range [Book1]Sheet1!$B$2>
0.9.0 新版功能.
- expand(mode='table')¶
根据要求的模式扩展单元格,不管左上角是否为空。(不像
Range.end()
).- 参数
mode (str, default 'table') – 可以取
'down'
,'right'
,``’table’`` (=down + right)。- 返回
- 返回类型
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range('A1').value = [[None, 1], [2, 3]] >>> xw.Range('A1').expand().address $A$1:$B$2 >>> xw.Range('A1').expand('right').address $A$1:$B$1
0.9.0 新版功能.
- property formula¶
对于给定的区域,获取或者设置公式。
- property formula2¶
Gets or sets the formula2 for the given Range.
- property formula_array¶
对于给定的区域,获取或者设置数组公式。
0.7.1 新版功能.
- get_address(row_absolute=True, column_absolute=True, include_sheetname=False, external=False)¶
用指定的格式返回区域的地址。当所有参数都是缺省的时候,和用
address
属性得到的结果是相同的。- 参数
row_absolute (bool, default True) – 设为
True
时,返回行部分的绝对引用。column_absolute (bool, default True) – 设为
True
时,返回列部分的绝对引用。include_sheetname (bool, default False) – 设为
True
时,返回的地址中包含工作表名。如果external=True
,不管这里的设置如何,都带工作表名。external (bool, default False) – 设为
True
时,返回带有工作簿名和工作表名的外部引用地址。
- 返回
- 返回类型
str
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range((1,1)).get_address() '$A$1' >>> xw.Range((1,1)).get_address(False, False) 'A1' >>> xw.Range((1,1), (3,3)).get_address(True, False, True) 'Sheet1!A$1:C$3' >>> xw.Range((1,1), (3,3)).get_address(True, False, external=True) '[Book1]Sheet1!A$1:C$3'
0.2.3 新版功能.
- property has_array¶
Are we part of an Array formula?
- property height¶
返回区域的高度,单位是点。 只读。
- 返回
- 返回类型
float
0.4.0 新版功能.
- property hyperlink¶
返回指定区域的超链接(仅适合单个单元格)
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range('A1').value 'www.xlwings.org' >>> xw.Range('A1').hyperlink 'http://www.xlwings.org'
0.3.0 新版功能.
- insert(shift=None, copy_origin='format_from_left_or_above')¶
在工作表中插入一个单元格或者一个区域。
- 参数
shift (str, default None) – 使用
right
ordown
。如果省略,Excel根据区域的形状决定。copy_origin (str, default format_from_left_or_above) – 可以用
format_from_left_or_above
或format_from_right_or_below
。注意macOS不支持这一特性。
- 返回
- 返回类型
None
- property last_cell¶
返回指定区域的右下角单元格。只读。
- 返回
- 返回类型
示例
>>> import xlwings as xw >>> wb = xw.Book() >>> rng = xw.Range('A1:E4') >>> rng.last_cell.row, rng.last_cell.column (4, 5)
0.3.5 新版功能.
- property left¶
返回A列的左边缘到区域的左边界的距离,单位点(point),只读。
- 返回
- 返回类型
float
0.6.0 新版功能.
- merge(across=False)¶
Creates a merged cell from the specified Range object.
- 参数
across (bool, default False) – True to merge cells in each row of the specified Range as separate merged cells.
- property merge_area¶
Returns a Range object that represents the merged Range containing the specified cell. If the specified cell isn’t in a merged range, this property returns the specified cell.
- property merge_cells¶
Returns
True
if the Range contains merged cells, otherwiseFalse
- property name¶
获取或者设置区域的名字。
0.4.0 新版功能.
- property note¶
Returns a Note object. Before the introduction of threaded comments, a Note was called a Comment.
0.24.2 新版功能.
- property number_format¶
获取或者设置区域的数字格式(
number_format
)。示例
>>> import xlwings as xw >>> wb = xw.Book() >>> xw.Range('A1').number_format 'General' >>> xw.Range('A1:C3').number_format = '0.00%' >>> xw.Range('A1:C3').number_format '0.00%'
0.2.3 新版功能.
- options(convert=None, **options)¶
允许用户设定转换器和相关的选项。转换器定义了Excel的区域及其值在读写过程中如何转换。如果没有明确指定转换器,会使用基转换器(base converter)。参考: 转换器及选项 。
- 参数
convert (object, default None) – 转换器名称,例如:
dict
,np.array
,pd.DataFrame
,pd.Series
等, 缺省时使用缺省转换器。- 关键字参数
ndim (int, default None) – 维数
numbers (type, default None) – 数字类型,如
int
dates (type, default None) – 例如
datetime.date
,缺省时是datetime.datetime
。empty (object, default None) – 空白单元格的转换
transpose (Boolean, default False) – 是否转置
expand (str, default None) – 可以取下列值:
'table'
,'down'
,'right'
。chunksize (int) –
- Use a chunksize, e.g.
10000
to prevent timeout or memory issues when reading or writing large amounts of data. Works with all formats, including DataFrames, NumPy arrays, and list of lists.
=> 与转换器有关的选项,参考: 转换器及选项 。
- Use a chunksize, e.g.
- 返回
- 返回类型
Range object
0.7.0 新版功能.
- paste(paste=None, operation=None, skip_blanks=False, transpose=False)¶
从剪贴板里拷贝一个区域到指定区域
- 参数
paste (str, default None) – 可以取下列值:
all_merging_conditional_formats
,all
,all_except_borders
,all_using_source_theme
,column_widths
,comments
,formats
,formulas
,formulas_and_number_formats
,validation
,values
,values_and_number_formats
.operation (str, default None) – 可以取下列值: “add”, “divide”, “multiply”, “subtract”。
skip_blanks (bool, default False) – 设为
True
时忽略空白单元格transpose (bool, default False) – 设为
True
时对行列转置
- 返回
- 返回类型
None
- property raw_value¶
不经过xlwings的数据处理,直接对底层引擎(
pywin32
或appscript
)处理的值进行读取或者设置。这样能够提升速度但是也自然就依赖底层引擎了,举例来说,可能就把跨平台的兼容性丢掉了。
- resize(row_size=None, column_size=None)¶
重新调整指定区域的大小。
- 参数
row_size (int > 0) – 新的区域的行数(如果为
None
, 区域保持原来的行数不变)。column_size (int > 0) – 新的区域的列数(如果为
None
, 区域保持原来的列数不变)。
- 返回
区域对象
- 返回类型
0.3.0 新版功能.
- property row¶
返回区域第一行的行号。只读。
- 返回
- 返回类型
Integer
0.3.5 新版功能.
- property row_height¶
取得或者设置区域的行高,单位是
point
。 如果区域内所有的行高度都一样,就返回这个高度。如果不一样,就返回None
。row_height必须在下列范围内: 0 <= row_height <= 409.5
注意:如果区域不在工作表已用区域内并且行高不同,返回第一行的高度。
- 返回
- 返回类型
float
0.4.0 新版功能.
- select()¶
选中区域。只能在活动的工作簿中选。
0.9.0 新版功能.
- property shape¶
表示区域范围的元组。
0.3.0 新版功能.
- property sheet¶
返回区域所属的工作表对象。
0.9.0 新版功能.
- property size¶
区域内的单元格数量。
0.3.0 新版功能.
- property table¶
Returns a Table object if the range is part of one, otherwise
None
.0.21.0 新版功能.
- to_png(path=None)¶
Exports the range as PNG picture.
- 参数
path (str or path-like, default None) – Path where you want to store the picture. Defaults to the name of the range in the same directory as the Excel file if the Excel file is stored and to the current working directory otherwise.
versionadded: (.) – 0.24.8:
- property top¶
返回从第一行的边缘到区域边缘的距离,单位是
point
,只读。- 返回
- 返回类型
float
0.6.0 新版功能.
- unmerge()¶
Separates a merged area into individual cells.
- property value¶
Gets and sets the values for the given Range. See see
xlwings.Range.options()
about how to set options, e.g. to transform it into a DataFrame or how to set a chunksize.- 返回
对象
- 返回类型
返回的对象依赖于所使用的转换器,参考:
xlwings.Range.options()
。
- property width¶
返回一个区域的宽度,单位是
point
,只读。- 返回
- 返回类型
float
0.4.0 新版功能.
- property wrap_text¶
Returns
True
if the wrap_text property is enabled andFalse
if it’s disabled. If not all cells have the same value in a range, on Windows it returnsNone
and on macOSFalse
.0.23.2 新版功能.
RangeRows¶
- class xlwings.RangeRows(rng)¶
代表一个区域内的所有行。不要直接创建这个对象,而是应该用
Range.rows
。示例
import xlwings as xw rng = xw.Range('A1:C4') assert len(rng.rows) == 4 # or rng.rows.count rng.rows[0].value = 'a' assert rng.rows[2] == xw.Range('A3:C3') assert rng.rows(2) == xw.Range('A2:C2') for r in rng.rows: print(r.address)
- autofit()¶
自动调整行高。
- property count¶
返回行数。
0.9.0 新版功能.
RangeColumns¶
- class xlwings.RangeColumns(rng)¶
代表一个区域的所有行。不要直接创建这个类,应该使用
Range.columns
。示例
import xlwings as xw rng = xw.Range('A1:C4') assert len(rng.columns) == 3 # or rng.columns.count rng.columns[0].value = 'a' assert rng.columns[2] == xw.Range('C1:C4') assert rng.columns(2) == xw.Range('B1:B4') for c in rng.columns: print(c.address)
- autofit()¶
自动调整列宽。
- property count¶
返回列的数量。
0.9.0 新版功能.
Shapes¶
- class xlwings.main.Shapes(impl)¶
在指定的工作表中的所有形状对象(
shape
)的集合:>>> import xlwings as xw >>> xw.books['Book1'].sheets[0].shapes Shapes([<Shape 'Oval 1' in <Sheet [Book1]Sheet1>>, <Shape 'Rectangle 1' in <Sheet [Book1]Sheet1>>])
0.9.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。
- property count¶
返回集合中的对象数。
Shape¶
- class xlwings.Shape(*args, **options)¶
是
shapes
集合中的一员:>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.shapes[0] # or sht.shapes['ShapeName'] <Shape 'Rectangle 1' in <Sheet [Book1]Sheet1>>
在 0.9.0 版更改.
- activate()¶
激活形状(shape)。
0.5.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.19.2 新版功能.
- delete()¶
删除形状。
0.5.0 新版功能.
- property height¶
返回或者设置形状的高度,单位是
point
。0.5.0 新版功能.
- property left¶
返回或者设置代表形状的水平位置,单位是
point
。0.5.0 新版功能.
- property name¶
返回形状的名称
0.5.0 新版功能.
- property parent¶
返回形状所属的对象。
0.9.0 新版功能.
- scale_height(factor, relative_to_original_size=False, scale='scale_from_top_left')¶
- factorfloat
For example 1.5 to scale it up to 150%
- relative_to_original_sizebool, optional
If
False
, it scales relative to current height (default). ForTrue
must be a picture or OLE object.- scalestr, optional
One of
scale_from_top_left
(default),scale_from_bottom_right
,scale_from_middle
0.19.2 新版功能.
- scale_width(factor, relative_to_original_size=False, scale='scale_from_top_left')¶
- factorfloat
For example 1.5 to scale it up to 150%
- relative_to_original_sizebool, optional
If
False
, it scales relative to current width (default). ForTrue
must be a picture or OLE object.- scalestr, optional
One of
scale_from_top_left
(default),scale_from_bottom_right
,scale_from_middle
0.19.2 新版功能.
- property text¶
Returns or sets the text of a shape.
0.21.4 新版功能.
- property top¶
返回或设置形状的垂直位置,单位为
point
。0.5.0 新版功能.
- property type¶
返回形状的类型。
0.9.0 新版功能.
- property width¶
返回或者设置形状的宽度,单位是
point
。0.5.0 新版功能.
Charts¶
- class xlwings.main.Charts(impl)¶
指定工作表中所有图表对象(
chart
)的集合:>>> import xlwings as xw >>> xw.books['Book1'].sheets[0].charts Charts([<Chart 'Chart 1' in <Sheet [Book1]Sheet1>>, <Chart 'Chart 1' in <Sheet [Book1]Sheet1>>])
0.9.0 新版功能.
- add(left=0, top=0, width=355, height=211)¶
在指定的工作表中创建一个新的图表。
- 参数
left (float, default 0) – 左边起点,单位是
point
。top (float, default 0) – 上边的起点,单位是
point
。width (float, default 355) – 宽带,单位是
point
。height (float, default 211) – 高度,单位是
point
。
- 返回
- 返回类型
示例
>>> import xlwings as xw >>> sht = xw.Book().sheets[0] >>> sht.range('A1').value = [['Foo1', 'Foo2'], [1, 2]] >>> chart = sht.charts.add() >>> chart.set_source_data(sht.range('A1').expand()) >>> chart.chart_type = 'line' >>> chart.name 'Chart1'
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。
- property count¶
返回集合中的对象数。
Chart¶
- class xlwings.Chart(name_or_index=None, impl=None)¶
chart对象是
charts
集合中的一员:>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.charts[0] # or sht.charts['ChartName'] <Chart 'Chart 1' in <Sheet [Book1]Sheet1>>
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- property chart_type¶
Returns and sets the chart type of the chart. The following chart types are available:
3d_area
,3d_area_stacked
,3d_area_stacked_100
,3d_bar_clustered
,3d_bar_stacked
,3d_bar_stacked_100
,3d_column
,3d_column_clustered
,3d_column_stacked
,3d_column_stacked_100
,3d_line
,3d_pie
,3d_pie_exploded
,area
,area_stacked
,area_stacked_100
,bar_clustered
,bar_of_pie
,bar_stacked
,bar_stacked_100
,bubble
,bubble_3d_effect
,column_clustered
,column_stacked
,column_stacked_100
,combination
,cone_bar_clustered
,cone_bar_stacked
,cone_bar_stacked_100
,cone_col
,cone_col_clustered
,cone_col_stacked
,cone_col_stacked_100
,cylinder_bar_clustered
,cylinder_bar_stacked
,cylinder_bar_stacked_100
,cylinder_col
,cylinder_col_clustered
,cylinder_col_stacked
,cylinder_col_stacked_100
,doughnut
,doughnut_exploded
,line
,line_markers
,line_markers_stacked
,line_markers_stacked_100
,line_stacked
,line_stacked_100
,pie
,pie_exploded
,pie_of_pie
,pyramid_bar_clustered
,pyramid_bar_stacked
,pyramid_bar_stacked_100
,pyramid_col
,pyramid_col_clustered
,pyramid_col_stacked
,pyramid_col_stacked_100
,radar
,radar_filled
,radar_markers
,stock_hlc
,stock_ohlc
,stock_vhlc
,stock_vohlc
,surface
,surface_top_view
,surface_top_view_wireframe
,surface_wireframe
,xy_scatter
,xy_scatter_lines
,xy_scatter_lines_no_markers
,xy_scatter_smooth
,xy_scatter_smooth_no_markers
0.1.1 新版功能.
- delete()¶
删除图表。
- property height¶
返回图表的高度,单位是
point
。
- property left¶
返回或者设置图表的水平位置,单位是
point
。
- property name¶
返回图表的名字。
- property parent¶
返回图表所属的对象。
0.9.0 新版功能.
- set_source_data(source)¶
设置图表的数据源区域。
- 参数
source (Range) – 区域对象,例如
xw.books['Book1'].sheets[0].range('A1')
- to_png(path=None)¶
Exports the chart as PNG picture.
- 参数
path (str or path-like, default None) – Path where you want to store the picture. Defaults to the name of the chart in the same directory as the Excel file if the Excel file is stored and to the current working directory otherwise.
versionadded: (.) – 0.24.8:
- property top¶
返回或者设置图表的垂直位置,单位是
point
。
- property width¶
返回图表的宽度,单位是
point
。
Pictures¶
- class xlwings.main.Pictures(impl)¶
指定工作表中图片(
picture
)对象的集合:>>> import xlwings as xw >>> xw.books['Book1'].sheets[0].pictures Pictures([<Picture 'Picture 1' in <Sheet [Book1]Sheet1>>, <Picture 'Picture 2' in <Sheet [Book1]Sheet1>>])
0.9.0 新版功能.
- add(image, link_to_file=False, save_with_document=True, left=None, top=None, width=None, height=None, name=None, update=False, scale=None, format=None, anchor=None)¶
在指定的工作表中增加一个图片。
- 参数
image (str or path-like object or matplotlib.figure.Figure) – 是文件路径名或者是Matplotlib图形对象。
left (float, default None) – Left position in points, defaults to 0. If you use
top
/left
, you must not provide a value foranchor
.top (float, default None) – Top position in points, defaults to 0. If you use
top
/left
, you must not provide a value foranchor
.width (float, default None) – Width in points. Defaults to original width.
height (float, default None) – Height in points. Defaults to original height.
name (str, default None) – Excel的图片名字。如果没有命名,缺省值是Excel的标准名字如:
‘Picture 1’
。update (bool, default False) – 替换指定名字的图片,需要指定图片名字。
scale (float, default None) – Scales your picture by the provided factor.
format (str, default None) – Only used if image is a Matplotlib or Plotly plot. By default, the plot is inserted in the “png” format, but you may want to change this to a vector-based format like “svg” on Windows (may require Microsoft 365) or “eps” on macOS for better print quality. If you use
'vector'
, it will be using'svg'
on Windows and'eps'
on macOS. To find out which formats your version of Excel supports, see: https://support.microsoft.com/en-us/topic/support-for-eps-images-has-been-turned-off-in-office-a069d664-4bcf-415e-a1b5-cbb0c334a840anchor (xw.Range, default None) –
The xlwings Range object of where you want to insert the picture. If you use
anchor
, you must not provide values fortop
/left
.0.24.3 新版功能.
- 返回
- 返回类型
示例
Picture
>>> import xlwings as xw >>> sht = xw.Book().sheets[0] >>> sht.pictures.add(r'C:\path\to\file.png') <Picture 'Picture 1' in <Sheet [Book1]Sheet1>>
Matplotlib
>>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.plot([1, 2, 3, 4, 5]) >>> sht.pictures.add(fig, name='MyPlot', update=True) <Picture 'MyPlot' in <Sheet [Book1]Sheet1>>
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。
- property count¶
返回集合中的对象数。
Picture¶
- class xlwings.Picture(impl=None)¶
图片对象是
pictures
集合中的一员:>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.pictures[0] # or sht.charts['PictureName'] <Picture 'Picture 1' in <Sheet [Book1]Sheet1>>
在 0.9.0 版更改.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- delete()¶
删除图片。
0.5.0 新版功能.
- property height¶
获得或者设置图片的高度,单位是
point
。0.5.0 新版功能.
- property left¶
获得或者设置图片的水平位置,单位是
point
。0.5.0 新版功能.
- property lock_aspect_ratio¶
True
will keep the original proportion,False
will allow you to change height and width independently of each other (read/write).0.24.0 新版功能.
- property name¶
获得或者设置图片的名字。
0.5.0 新版功能.
- property parent¶
返回图片所属的对象。
0.9.0 新版功能.
- property top¶
获得或者设置图片的垂直位置,单位是
point
。0.5.0 新版功能.
- update(image, format=None)¶
用新的图片替换原有的图片,继承原来图片的属性。
- 参数
image (str or path-like object or matplotlib.figure.Figure) – 是文件路径名或者是Matplotlib图形对象。
0.5.0 新版功能.
- property width¶
获得或者设置图片的宽度,单位是
point
。0.5.0 新版功能.
Names¶
- class xlwings.main.Names(impl)¶
工作簿中所有名称(
name
)对象的集合:>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.names [<Name 'MyName': =Sheet1!$A$3>]
0.9.0 新版功能.
- add(name, refers_to)¶
为一个单元格组成的区域定义名称。
- 参数
name (str) – 指定作为名称的文字。名称中不能包含空格,也不能是单元格的引用。
refers_to (str) – 使用英语,按照
A1表示法
描述名称引用的具体内容
- 返回
- 返回类型
0.9.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- property count¶
返回集合中的对象数。
Name¶
- class xlwings.Name(impl)¶
一个name对象是names集合中的一员:
>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.names[0] # or sht.names['MyName'] <Name 'MyName': =Sheet1!$A$3>
0.9.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.9.0 新版功能.
- delete()¶
删除名称。
0.9.0 新版功能.
- property name¶
返回或者设置命名对象的名称。
0.9.0 新版功能.
- property refers_to¶
返回或者设置名称引用的公式,公式以等号开头,采用
A1表示法
。0.9.0 新版功能.
- property refers_to_range¶
返回命名对象引用的区域对象。
0.9.0 新版功能.
Note¶
- class xlwings.main.Note(impl)¶
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.24.2 新版功能.
- delete()¶
Delete the note.
0.24.2 新版功能.
- property text¶
Gets or sets the text of a note. Keep in mind that the note must already exist!
示例
>>> sheet = xw.Book(...).sheets[0] >>> sheet['A1'].note.text = 'mynote' >>> sheet['A1'].note.text >>> 'mynote'
0.24.2 新版功能.
Tables¶
- class xlwings.main.Tables(impl)¶
A collection of all
table
objects on the specified sheet:>>> import xlwings as xw >>> xw.books['Book1'].sheets[0].tables Tables([<Table 'Table1' in <Sheet [Book11]Sheet1>>, <Table 'Table2' in <Sheet [Book11]Sheet1>>])
0.21.0 新版功能.
- add(source=None, name=None, source_type=None, link_source=None, has_headers=True, destination=None, table_style_name='TableStyleMedium2')¶
Creates a Table to the specified sheet.
- 参数
source (xlwings range, default None) – An xlwings range object, representing the data source.
name (str, default None) – The name of the Table. By default, it uses the autogenerated name that is assigned by Excel.
source_type (str, default None) – This currently defaults to
xlSrcRange
, i.e. expects an xlwings range object. No other options are allowed at the moment.link_source (bool, default None) – Currently not implemented as this is only in case
source_type
isxlSrcExternal
.has_headers (bool or str, default True) – Indicates whether the data being imported has column labels. Defaults to
True
. Possible values:True
,FAlse
,'guess'
destination (xlwings range, default None) – Currently not implemented as this is used in case
source_type
isxlSrcExternal
.table_style_name (str, default 'TableStyleMedium2') – Possible strings:
'TableStyleLightN''
(where N is 1-21),'TableStyleMediumN'
(where N is 1-28),'TableStyleDarkN'
(where N is 1-11)
- 返回
- 返回类型
示例
>>> import xlwings as xw >>> sheet = xw.Book().sheets[0] >>> sheet['A1'].value = [['a', 'b'], [1, 2]] >>> table = sheet.tables.add(source=sheet['A1'].expand(), name='MyTable') >>> table <Table 'MyTable' in <Sheet [Book1]Sheet1>>
Table¶
- class xlwings.main.Table(*args, **options)¶
The table object is a member of the
tables
collection:>>> import xlwings as xw >>> sht = xw.books['Book1'].sheets[0] >>> sht.tables[0] # or sht.tables['TableName'] <Table 'Table 1' in <Sheet [Book1]Sheet1>>
0.21.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。
- property data_body_range¶
Returns an xlwings range object that represents the range of values, excluding the header row
- property display_name¶
Returns or sets the display name for the specified Table object
- property header_row_range¶
Returns an xlwings range object that represents the range of the header row
- property insert_row_range¶
Returns an xlwings range object representing the row where data is going to be inserted. This is only available for empty tables, otherwise it’ll return
None
- property name¶
Returns or sets the name of the Table.
- property parent¶
Returns the parent of the table.
- property range¶
Returns an xlwings range object of the table.
- resize(range)¶
Resize a Table by providing an xlwings range object
0.24.4 新版功能.
- property show_autofilter¶
Turn the autofilter on or off by setting it to
True
orFalse
(read/write boolean)
- property show_headers¶
Show or hide the header (read/write)
- property show_table_style_column_stripes¶
Returns or sets if the Column Stripes table style is used for (read/write boolean)
- property show_table_style_first_column¶
Returns or sets if the first column is formatted (read/write boolean)
- property show_table_style_last_column¶
Returns or sets if the last column is displayed (read/write boolean)
- property show_table_style_row_stripes¶
Returns or sets if the Row Stripes table style is used (read/write boolean)
- property show_totals¶
Gets or sets a boolean to show/hide the Total row.
- property table_style¶
Gets or sets the table style. See
Tables.add
for possible values.
- property totals_row_range¶
Returns an xlwings range object representing the Total row
- update(data, index=True)¶
Updates the Excel table with the provided data. Currently restricted to DataFrames.
在 0.24.0 版更改.
- 参数
data (pandas DataFrame) – Currently restricted to pandas DataFrames.
index (bool, default True) – Whether or not the index of a pandas DataFrame should be written to the Excel table.
- 返回
- 返回类型
示例
import pandas as pd import xlwings as xw sheet = xw.Book('Book1.xlsx').sheets[0] table_name = 'mytable' # Sample DataFrame nrows, ncols = 3, 3 df = pd.DataFrame(data=nrows * [ncols * ['test']], columns=['col ' + str(i) for i in range(ncols)]) # Hide the index, then insert a new table if it doesn't exist yet, # otherwise update the existing one df = df.set_index('col 0') if table_name in [table.name for table in sheet.tables]: sheet.tables[table_name].update(df) else: mytable = sheet.tables.add(source=sheet['A1'], name=table_name).update(df)
Font¶
- class xlwings.main.Font(impl)¶
The font object can be accessed as an attribute of the range or shape object.
mysheet['A1'].font
mysheet.shapes[0].font
0.23.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.23.0 新版功能.
- property bold¶
Returns or sets the bold property (boolean).
>>> sheet['A1'].font.bold = True >>> sheet['A1'].font.bold True
0.23.0 新版功能.
- property color¶
Returns or sets the color property (tuple).
>>> sheet['A1'].font.color = (255, 0, 0) # or '#ff0000' >>> sheet['A1'].font.color (255, 0, 0)
0.23.0 新版功能.
- property italic¶
Returns or sets the italic property (boolean).
>>> sheet['A1'].font.italic = True >>> sheet['A1'].font.italic True
0.23.0 新版功能.
- property name¶
Returns or sets the name of the font (str).
>>> sheet['A1'].font.name = 'Calibri' >>> sheet['A1'].font.name Calibri
0.23.0 新版功能.
- property size¶
Returns or sets the size (float).
>>> sheet['A1'].font.size = 13 >>> sheet['A1'].font.size 13
0.23.0 新版功能.
Characters¶
- class xlwings.main.Characters(impl)¶
The characters object can be accessed as an attribute of the range or shape object.
mysheet['A1'].characters
mysheet.shapes[0].characters
注解
On macOS,
characters
are currently not supported due to bugs/lack of support in AppleScript.0.23.0 新版功能.
- property api¶
返回正在使用的引擎的原生对象(
pywin32
或appscript
对象)。0.23.0 新版功能.
- property font¶
Returns or sets the text property of a
characters
object.>>> sheet['A1'].characters[1:3].font.bold = True >>> sheet['A1'].characters[1:3].font.bold True
0.23.0 新版功能.
- property text¶
Returns or sets the text property of a
characters
object.>>> sheet['A1'].value = 'Python' >>> sheet['A1'].characters[:3].text Pyt
0.23.0 新版功能.
Markdown¶
MarkdownStyle¶
UDF装饰器¶
- xlwings.func(category='xlwings', volatile=False, call_in_wizard=True)¶
在运行 “Import Python UDFs” 的时候,被
xlwings.func
装饰过的函数会被作为Function(函数)
导入到Excel。- categoryint 或 str, 缺省值 “xlwings”
1-14代表内置类别,用户定义类别使用字符串
0.10.3 新版功能.
- volatilebool类型, 缺省值为False
把一个用户定义函数标记为易变的。当工作表中的任意单元格发生计算的时候,都必须重新计算易变的函数的值。非易变函数只有在输入变量变化的时候才重新进行计算。当不在用于计算工作表的单元格的用户定义函数中是,此方法不起作用。
0.10.3 新版功能.
- call_in_wizardbool类型, 缺省值为True
设置为False时,抑制公式向导中的函数调用。
0.10.3 新版功能.
- xlwings.sub()¶
使用装饰器
xlwings.sub
装饰的函数,在运行”Import Python UDFs”时,会被作为Sub
(例如:宏)导入到Excel。
- xlwings.arg(arg, convert=None, **options)¶
对参数应用转换器及其选项,参见
Range.options()
。示例:
把
x
转换为2维numpy数组:import xlwings as xw import numpy as np @xw.func @xw.arg('x', np.array, ndim=2) def add_one(x): return x + 1
- xlwings.ret(convert=None, **options)¶
对返回值应用转换器及其选项,参见
Range.options()
。示例:
抑制返回的DataFrame中的索引和表头:
import pandas as pd @xw.func @xw.ret(index=False, header=False) def get_dataframe(n, m): return pd.DataFrame(np.arange(n * m).reshape((n, m)))
动态数组:
注解
If your version of Excel supports the new native dynamic arrays, then you don’t have to do anything special, and you shouldn’t use the
expand
decorator! To check if your version of Excel supports it, see if you have the=UNIQUE()
formula available. Native dynamic arrays were introduced in Office 365 Insider Fast at the end of September 2018.expand='table'
把UDF转变为动态数组。目前在动态数组中不能使用易变函数,比如,不能用=TODAY()
作为动态数组的一部分。同时注意动态数组需要在右边和底部有一个空的行或列(以便确定区域范围)而且在覆盖数据时不会发出提醒信息。不像标准的Excel数组,动态数组是在一个单元格中作为标准函数使用的,它会根据返回数组的范围自动扩展:
import xlwings as xw import numpy as np @xw.func @xw.ret(expand='table') def dynamic_array(n, m): return np.arange(n * m).reshape((n, m))
0.10.0 新版功能.