Python - Excel operation module xlwings

xlwings

When it comes to Python operations Excel, there are a lot of modules can support this work. For example, the bottom of the win32 module can operate not only Excel, you can also operate other windows of a public software.

There are other more familiar xlrd, xlwt and xlutils three. Excel files are responsible for reading, writing, reading and writing conversion work. Although Excel operation under normal circumstances can be done by these three modules, but there are still many inconvenient places. Cell formatting such as reading and writing a lot of trouble, read by an Excel xlutils then written to a new file will not be copied over format together.

I recently met another demand is based on an Excel template, populate the data entered. While templates can be converted to xlwt code written died in the build script, but every time to re-generate a file was too much trouble, and a lattice grid to a rapid rise in the amount of code written to make. . In desperation to find another way, tried to use the xlwings this module.
  ## Basic use
   and xlrd so different, the basic design concept xlwings not for a single Excel document, but can handle a contains "Excel Project" multiple Excel documents. By establishing the concept of the logical components of its app, etc., you can make the whole project Excel can easily calculate and communicate with each other more orderly. Concept Hierarchy of each model xlwings design as shown below:
   Here Insert Picture Description wherein App as a logical grouping of a corresponding one of Book believed Excel document, Sheet corresponding to a worksheet, the Range content corresponding to a specific area in the table. First, here is one of the most common, open an Excel document and process a simple process:

import xlwings as xw

book = xw.Book('/path/to/test.xlsx')
# 此时界面上会弹出Excel窗口,如果test.xlsx文件不存在则会报错,如果test.xlsx已经被打开,直接返回这个文件对象

print book.name,book.fullname    # 打印文件名和绝对路径
print book.app    # 可以查看book所在哪个APP
print book.sheets    # 又是一个类列表结构,存放各种Sheet对象
book.activate()    # 如果Excel没有获得当前系统的焦点,调用这个方法可以回到Excel中去
book.close()    # 关闭Excel文档,但只是关闭文件本身,不关闭excel程序。。若要关闭Excel程序则需要调用响应APP实例的kill方法。经过试验,先调用close会导致默认创建的app实例自动消失,从而无法调用kill,从而关不掉Excel
所以最好的办法不是调用这个close而是调用app.kill()。

sheet = book.sheets[0]
# 其他获取sheet对象的方法还有book.sheets['sheet_name']

When it comes to the top to get a specific sheet, a sheet can be called natural methods are:

sheet.activate
– sheet.charts –
sheet.index
sheet.api –
sheet.clear
sheet.name
sheet.autofit
sheet.clear_contents
sheet.names
sheet.book
sheet.delete
sheet.pictures
sheet.cells
sheet.impl
sheet.range

Wherein activate, autofit, cliear_content other such methods are quite interesting. The method should be the most central range, you can get to the specific data for a certain period of range through it.

E.g. sheet.range ( 'A1') of the cell A1 acquired the object, this object is accessible through the attribute value, can read / change the value of the cell, and all this without affecting the format of the cell itself.

One approach is more imba sheet.range ( 'A1: C3') such forms may be obtained one time to the subject all the cells in an area. Transfer target, then get whichever value is also a form of two-dimensional list of data collection, you can easily map the image data to Excel in python in the past. For setting data, the incoming data may be pointed out that a structure does not comply with the provisions of the area, but this result would be more subtle. . Suggested Experiments

And xlrd should be noted that the same value is read only when the merged cells in the value of its sub-cell in the upper left corner, and as the rest of the unfilled cells are None.

For range, we can do much more

In addition to simply call value and for the value assigned to read and write Excel, there are the following interfaces can be used

range.add_hyperlink
range.clear_contents
range.count
range.address
range.color
range.current_region
range.api
range.column
range.end
range.autofit
range.column_width
range.expand
range.clear
range.columns
range.formula
…等等

Some use interface tips:

range.add_hyperlink(‘https://www.baidu.com’,‘百度’)

   range.color = (128,128,128)    RGB通道颜色,可获取or设置

range.row / column get the first few rows / columns, rather than pay attention to the first few subscript

range.formula calculation expression can be provided, in the table for calculation

range.current_region return region of the range where the expression of the current area, the more difficult is described, such a one, not between the two sheets in Excel cells are connected to each other Liancheng any adjacent to each other is independent.

range.count return to this range in the total number of cells, merge cells are still considered by unconsolidated

range.offset (a, b) acquiring a right to the current range cell, cell b is moved downward in that area the same size, ab can be negative

range.rows / columns each range target return row / column

■ About App

In fact, App has not carefully studied, in simple terms, when an instance is created by xw.Book, the default App instance to add a xw.apps rather book fall into this App.

As mentioned above, to solve the problem can not be closed Excel program can use this method kill app instance. app.kill () can put together the Excel program together with the file is closed. In addition, if you do not have Excel, you can set the program to jump out app.visible = False, instant set up with immediate effect.

Because usually our operations based on Book class object, when finished book.save, if you want to turn off Excel, you can call book.app.kill () or book.app.quit (), but before that do not book. close (), otherwise it will error oh. (Recommended quit, using a kill, then open some excel software such as WPS will record a non-normal exit status, when you open the document again when the error will say there is an error. If the second still use xlwings open, but the error occupied the focus of the dialog box, make xlwings will not work properly).

Published 58 original articles · won praise 14 · views 9323

Guess you like

Origin blog.csdn.net/lh_hebine/article/details/104302143