Super complete finishing|Python operation Excel library xlwings common operation detailed explanation!

Click on " Python crawler and data mining " above to follow

Reply to " Books " to receive a total of 10 e-books of Python from beginner to advanced

now

day

Chickens

soup

Xiang Wanyi feels unwell and drove to Guyuan.


Hello everyone, I wake up early.

In the previous article we have explained in detail how to use the openpyxloperating Excel, in fact, there are other Python libraries can directly manipulate Excel files, such as xlwings, xlrd, xlwtand so on, this article will explain another excellent libraryxlwings

At the beginning or would like to talk, there is no clear distinction between good and bad of each library, each library has its appropriate application scenarios, and xlwingsand openpyxlmany differences determine their capabilities are complementary:

xlwings: Need to have Excel software, support .xlsand .xlsxformat; you can call Excel VBA file written procedures; and matplotlibas well as pandasthe compatibility

openpyxl: Excel does not require software only supports .xlsxformats

installation

xlwings It is a non-standard library and needs to be installed on the command line. You can install it using pip in the terminal (Mac)/command line (Win). Generally, there will be no problems.

pip install xlwings

Pre-knowledge

On the xlwingscore understanding is that the picture below:

Can be seen, and xlwingsdirect docking is apps, which is Excel application, and then the workbook booksand worksheet sheets, and this openpyxlis quite different, it is precisely because of this, xlwingsthe need is still installed Excel application environment

Detailed code

1. Open the Excel program

Open with app

import xlwings as xw
app = xw.App(visible=True, add_book=False) # 程序可见,只打开不新建工作薄
app.display_alerts = False # 警告关闭
app.screen_updating = False # 屏幕更新关闭

Two, save, exit, close

It should be noted, as xlwingsis the procedure apps as the primary operating target, and therefore the first and last are based app on and off

path = r"C:\Scientific Research\Python"
wb = app.books.open(path + r'\practice.xlsx')
wb.save() # 保存文件
wb.close() # 关闭文件
app.quit() # 关闭程序

Open the table and divide it into two situations, namely fixed and active:

xw.Book(path + r'\practice.xlsx')   # 固定打开表格
xw.books.open(path + r'\practice.xlsx') # 频繁打开表格

Fixed and frequent open involves a concept called active objects , it makes xlwingsthe operation more flexible:

# 活动应用程序
app = xw.apps.active

# 活动工作簿
wb = xw.books.active  # 在活动app
wb = app.books.active  # 在特定app

# 活动工作表
sheet = xw.sheets.active  # 在活动工作簿
sheet = wb.sheets.active  # 在特定工作簿

# 活动工作表的Range
xw.Range('A1') 

Three, create a new Excel file

Remember to save the workbook, close the workbook, and close the program whether it is new or open

path = r"C:\Scientific Research\Python"
wb = app.books.add()
wb.save(path + r'\new_practice.xlsx') 
wb.close() 
app.quit() 

Four, read the content

Sample files practice.xlsxare as follows:

The following code part no longer displays the opening and closing code of the program, which is conducive to visually see the key points:

path = r"C:\Scientific Research\Python"
wb = app.books.open(path + r'\practice.xlsx')
# 类似 openpyxl 中的 sheet = workbook.active
sheet = wb.sheets.active

# 获取单个单元格的值
A1 = sheet.range('A1').value
print(A1)
# 获取横向或纵向多个单元格的值,返回列表
A1_A3 = sheet.range('A1:A3').value
print(A1_A3)
# 获取给定范围内多个单元格的值,返回嵌套列表,按行为列表
A1_C4 = sheet.range('A1:C4').value
print(A1_C4)

In xlwings can by sheet.rangeoperating one or more cells acquired, may not additionally sheet.rangeacquired:

# 获取单个单元格的值
A1 = sheet['A1'].value
print(A1)
# 获取横向或纵向多个单元格的值,返回列表
A1_A3 = sheet['A1:A3'].value
print(A1_A3)
# 获取给定范围内多个单元格的值,返回嵌套列表,按行为列表
A1_C4 = sheet['A1:C4'].value
print(A1_C4)

Whether a single cell or multiple cells can be used to .valuedirectly obtain, output and use .rangeexactly the same, but also to avoid similar openpyxlto get the value for a plurality of cells required to re-establish loop through.

An instrument pandasslicing method of obtaining all the value in the range:

sheet = wb.sheets.active
A1_B2 = sheet[:2, :2].value
print(A1_B2)

Five, write data

The following is the code for writing one cell, one row or one column, multiple cells, multiple cells in the range

# 写入 1 个单元格
sheet.range('A2').value = '大明'

# 一行或一列写入多个单元格
# 横向写入A1:C1
sheet.range('A1').value = [1,2,3]
# 纵向写入A1:A3
sheet.range('A1').options(transpose=True).value = [1,2,3]

# 写入范围内多个单元格
sheet.range('A1').options(expand='table').value = [[1,2,3], [4,5,6]]

For example, if give practice.xlsxadding a new record line, as follows:

import xlwings as xw
app = xw.App(visible=True, add_book=False)
app.display_alerts = False
app.screen_updating = False

path = r"C:\Scientific Research\Python"
wb = app.books.open(path + r'\practice.xlsx')
sheet = wb.sheets.active
sheet.range('A5').value = ['小兰', 23, '女']

wb.save()
wb.close()
app.quit()

Six, the scope of data acquisition

There are two ways to achieve

# 方法一
shape = sheet.used_range.shape
print(shape)

# 方法二
nrow = sheet.api.UsedRange.Rows.count
ncol = sheet.api.UsedRange.Columns.count
print(nrow)
print(ncol)

Seven, output and modify the row height and column width

# 输出
print(sheet.range('A1:A2').row_height)
print(sheet.range('A1:A2').column_width)
# 修改
sheet.range('A1:A2').row_height = 15
sheet.range('A1:A2').column_width = 10

8. Get and set formula

You can call Excel formulas, which cannot be done by pandas

# 获取公式
print(sheet.range('B2').formula_array)
# 写入公式
sheet.range('B2').formula='=SUM(A1,A2)'

Nine, get, set and clear the color format

Of course, style modifications like openpyxl are also supported

# 获取颜色
print(sheet.range('C1').color)
# 设置颜色
sheet.range('C1').color = (255, 0, 120)
# 清除颜色
sheet.range('C1').color = None

The above are only code examples and explanations for some common operations. For more operations, you can read the official documents. You can also compare xlwingsthe similarities and differences with other libraries in some operations. In the future, we will also update office automation cases based on xlwings!

------------------- End -------------------

Recommendations of previous wonderful articles:

Welcome everyone to like , leave a message, forward, reprint, thank you for your company and support

If you want to join the Python learning group, please reply in the background [ Enter the group ]

Thousands of rivers and mountains are always in love, can you click [ Looking ]

/Today's message topic/

Just say a word or two~~

Guess you like

Origin blog.csdn.net/pdcfighting/article/details/113830116