xlwingsチュートリアル
Xlwings Tutorial
xlwingsの紹介
PythonはExcelモジュールを操作します。インターネットで言及されているモジュールは、おおまかにxlwings、xlrd、xlwt、openpyxl、pyxllなどです。それらが提供する関数は2つの方法で要約できます。1。Pythonを使用してExcelファイルを読み書きします。Excelファイルは実際に読み書きされます。フォーマットされたテキストファイルの場合、Excelファイルとテキストおよびcsvファイルの操作に違いはありません。 Excelファイルはデータの保存にのみ使用されます。 2.操作データに加えて、Excelファイルのテーブル幅とフォントの色を調整することもできます。さらに、COMを使用してExcel APIを呼び出してExcelドキュメントを操作することも可能であることに注意してください。これは非常に面倒で、基本的にVBAとの違いはありません。
xlwings中国語ドキュメント
https://www.kancloud.cn/gnefnuy/xlwings-docs/1127474
xlwingsの機能
- xlwingsは、Excelファイルのデータを非常に便利に読み書きでき、セル形式を変更できます。
- matplotlibやパンダとシームレスに接続できます
- ExcelファイルでVBAで記述されたプログラムを呼び出すか、Pythonで記述されたプログラムをVBAに呼び出すことができます。
- オープンソースで無料、常に更新
基本操作
1つは、ライブラリをインポートする
import xlwings as xw
第二に、オープンエクセル
# Open the Excel program, the default setting: the program is visible, only open without creating a new workbook, and the screen update is closed app=xw.App(visible=True,add_book=False) app.display_alerts=False app.screen_updating=False # Other operations: # app.screen_updating = False #: Screen update means that you can see the code for the operation of excel. Turning off the real-time update can speed up the script running. The default is True. # app.pid #App process pid # app.books #Return to a list of all open workbooks. Python opened and manually opened are not interoperable # Terminate the process and force exit. # app.quit() #Without saving, exit the excel program
3、ワークブック
ブックを最初に開く必要があることに注意してください
1.新しいExcelドキュメントを作成します
wb = app.books.add() #Create new book wk = xw.Book() wk = xw.books.add()
2.Excelドキュメントを開きます
# Support absolute path and relative path wb = app.books.open('filepath') wk = xw.Book('filepath') wk = xw.books.open('filepath') # It is recommended to use the following directly when practicing # wb = xw.Book('example.xlsx') # In this case, you will not open new Excel frequently
3.保存されていないまたは閉じられていないExcelインスタンスを開きます
wk = xw.Book('Book1') wk = xw.books['Book1'] #You can also use the index
同じファイルを2つのExcelインスタンスで開く場合は、ファイルを完全に修飾し、アプリケーションインスタンスを含める必要があります。 xw.apps.keys()を介してアプリケーションインスタンスキー(PID)を見つけます。
xw.apps[10559].books['FileName.xlsx'] View all instance processes: xw.apps.keys() #Output list Kill all instance processes: for i in xw.apps.keys(): i = 'taskkill/pid ' + str(i) + ' -t -f' os.system(i)
4.アクティブなブックを開きます
wb = xw.books.active
5.保存
wb.save(path=None) # Save the workbook, if it is the specified path, save it in the current working directory.
6.閉じる
wk.close() #Close without saving.
7.Excelを終了します
app.quit()
4、ワークシート
1.ワークシートを開きます
# You can use the name or index sheet = xw.books['Name of workbook'].sheets['sheet's name'] sheet = xw.books['Name of workbook'].sheets[0]
2.アクティブなワークシートを開きます
sheet = xw.sheets.active
3.シートで指定された本を返却します
book_name = sheet.book
4.シート上のすべてのセルを表す範囲オブジェクトを返します
sheet_cells = sheet.cells
5.シートの名前を取得または設定します
sheet.name # Return all worksheets with specific names. sheet_names_list = sheet.names
6.シート内のすべてのチャートコレクションを取得します
sheet.charts
7.テーブル内のすべてのデータとフォーマットをクリアします。
sheet.clear()
8.ワークシートの内容をクリアしますが、フォーマットは保持します
sheet.clear_contents()
9、ワークシートを削除します
sheet.delete()
10.テーブルインデックスを返します(Excelと同じ)
sheet.index
11.新しいシートを作成し、それをアクティブシートにします
wb.sheets.add(name=None, before=None, after=None) #Parameter: name(str,default None)-the name of the new worksheet. If it is None, the default is Excel's name.before (Sheet, default None)-an object that specifies the added.after (Sheet, default None) before the new worksheet is added-specifies the object table of the worksheet after the worksheet added.
12.ワークシート全体の列、行、またはその両方の幅を自動的に調整します
sheet.autofit(axis=None) # Parameter: axis (string, default None)-To automatically adjust rows, use one of the following: rows or r, to automatically adjust columns, use one of the following: columns h c, to automatically adjust rows and columns, no parameters are provided
13.Excelシートの行と列の数を取得します
app = xw.App(visible=False, add_book=False) xls = app.books.open(excel_file) sheet = xls.sheets[0] info = sheet.used_range nrows = info.last_cell.row ncols = info.last_cell.colum
5、セル
1.A1セルを引用します
rng = xw.books['Name of workbook'].sheets['sheet's name'] # Or sheet=xw.books['Name of workbook'].sheets['sheet's name'] rng=sheet.range('A1')
2.アクティブなワークシートのセルを引用します
# Note that the first letter of Range is capitalized rng=xw.Range('A1') It should be noted that the full reference path of the cell is: # The first cell of the first sheet of the first workbook of the first Excel program xw.apps[0].books[0].sheets[0].range('A1') The way to quickly reference cells is sht=xw.books['first name'].sheets['first name'] # A1 cell rng=sht[’A1'] rng=sht['a1'] # A1:B5 cell rng=sht['A1:B5'] # The first column of the first row is a1 rng=sht[0,0] # B1 cell rng=sht[0,1]
3.参照領域セル
# A1:J10 rng=sht[:10,:10] rng=sht.range('a1:a5') #rng = sht['a1:a5'] #rng = sht[:5,0]
PS:セルの場合、参照用にランクと列を表すタプルを使用することもできます
# A1 cell reference xw.Range(1,1) #A1: C3 cell reference xw.Range((1,1),(3,3))
6、データを書き込む
1.単一の値を書き込む
# Note '.value' sht.range('A1').value=1
2.リストに書き込む
デフォルトで行ごとに挿入
# Store the list [1,2,3] in A1: C1 sht.range('A1').value=[1,2,3] # Equivalent to sht.range('A1:A3').value = [1,2,3]
列ごとに挿入
# Store the list [1,2,3] in A1:A3 sht.range('A1').options(transpose=True).value=[1,2,3]
複数行の入力には2次元のリストが必要です
# Store the 2x2 table, which is a two-dimensional array, in A1:B2, such as the first row 1, 2, and the second row 3, 4 sht.range('A1').options(expand='table').value=[[1,2],[3,4]]
セブン、データを読む
1.単一の値を読み取ります
# Read the value of A1 into a variable a=sht.range('A1').value
2.読み取り範囲の値
戻り値はリスト形式であり、2次元リストとして複数の行と複数の列がありますが、戻り値はデフォルトで浮動小数点数であることに注意してください。
#Read the values from A1 to A2 into the a list a=sht.range('A1:A2').value # Read the data in the first row and the second row in a two-dimensional array a=sht.range('A1:B2').value
Excelの最初の列を読み取り、最初にセルの行数を数えます
rng = sht.range('a1').expand('table') nrows = rng.rows.count
その後、あなたは正確な範囲で読むことができます
a = sht.range(f'a1:a{nrows}').value
データの行を選択する場合も同様です。
ncols = rng.columns.count #Use slices fst_col = sht[0,:ncols].value
8.一般的な機能と方法
1.ブックワークブックの一般的なAPI
# New workbook xw.books.add() # Reference the current active workbook xw.books.active wb=xw.books[‘Workbook name’] wb.activate()Activate as current workbook wb.fullname returns the absolute path of the workbook wb.name returns the name of the workbook wb.save(path=None) Save the workbook, the default path is the original path of the workbook, if not saved, it is the path where the script is located -wb. close() Close workbook Code example: # Refer to the current workbook in the Excel program wb=xw.books.acitve # Return the absolute path of the workbook x=wb.fullname # Return the name of the workbook x=wb.name # Save the workbook, the default path is the original path of the workbook, if not saved, it is the path where the script is located x=wb.save(path=None) # Close workbook x=wb.close()
2.一般的に使用されるAPIのシート
# New worksheet xw.sheets.add(name=None,before=None,after=None) # Refer to the current active sheet xw.sheets.active # Refer to a specified sheet sht=xw.books['Workbook name'].sheets['Name of the sheet'] # Activate sheet as the active worksheet sht.activate() # Clear the content and format of the sheet sht.clear() # Clear the contents of the sheet sht.contents() # Get the name of the sheet sht.name # Delete sheet sht.delete
3.一般的に使用されるAPIの範囲
# Refer to the cell of the current active worksheet rng=xw.Range('A1') # Add hyperlink # rng.add_hyperlink(r'www.baidu.com','Baidu','hint: click to link to Baidu') # Get the address of the current range rng.address rng.get_address() # Clear the content of range rng.clear_contents() # Clear format and content rng.clear() # Get the background color of the range and return the RGB value as a tuple rng.color # Set the color of the range rng.color=(255,255,255) # Clear the background color of the range rng.color=None # Get the first column label of the range rng.column # Return the data of the cell in the range rng.count # Return to current_region rng.current_region # Return ctrl + direction rng.end('down') # Get formula or enter formula rng.formula='=SUM(B1:B5)' # Array formula rng.formula_array # Get the absolute address of the cell rng.get_address(row_absolute=True, column_absolute=True,include_sheetname=False, external=False) # Get column width rng.column_width # Return the total width of the range rng.width # Get range hyperlink rng.hyperlink # Get the last cell in the lower right corner of the range rng.last_cell # range shift rng.offset(row_offset=0,column_offset=0) #rangeresize Changing the size of the range rng.resize(row_size=None,column_size=None) # The first line of the range rng.row # The height of the row, all rows are the same height, return the row height, if not the same, return None rng.row_height # Return the total height of the range rng.height # Return the number of rows and columns of the range rng.shape # Return the sheet where the range is located rng.sheet #Return all rows of range rng.rows # first line of range rng.rows[0] # The total number of rows in the range rng.rows.count # Return all columns of range rng.columns # Return the first column of range rng.columns[0] # Return the number of columns in the range rng.columns.count # The size of all ranges is adaptive rng.autofit() # All column widths are adaptive rng.columns.autofit() # All line width adaptive rng.rows.autofit()
著者:LuckyFrog
リンク:https://www.jianshu.com/p/e21894fc5501
出典:建州
著作権は作者に帰属します。
参考資料:
https://docs.xlwings.org/en/stable/index.html
https://www.kancloud.cn/gnefnuy/xlwings-docs/1127450