1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでExcelのフィルタリング結果を別ブックに保存する

Posted at

背景

Excelファイルでフィルタリングした結果を別のExcelとして保存していくプログラムを、VBAで作成しようとしたところあまりのコードの長さにうんざり。

目的

PythonのPandasを利用すると簡単に書けそうだったのでやってみた。

xlwt, openpyxlのインストール

to_excel()というライブラリを使用する。
xlwt, openpyxlがインストールされていなければインストールしておく。

$ pip install xlwt
$ pip install openpyxl

インポート

# Excelファイルをフィルタリングした結果をExcelファイルに保存する
import pandas as pd
import os

編集したいExcelファイルのディレクトリやら名前やら

dir_path = './jukosha' #編集したいExcelファイルのディレクトリ
file_name = 'jukosha.xlsx' #ファイル名
file_path = os.path.join(dir_path,file_name) #ファイルのパスを作成
sheetname = '所属' #編集したいシート名

Pandasでフィルタリング結果を抽出し、保存する

df_shozoku = pd.read_excel(file_path, sheet_name=sheetname)
df_taisho_all = df_shozoku[df_shozoku['対象者']=="〇"] #対象者をフィルタリング
df_bumon = df_taisho_all['部門コード名'].unique() #一意な部門コード名

# フィルタリングして別ファイルに保存していく
for i in range(len(df_bumon)):
    bumon_codename = df_bumon[i]
    df=df_taisho_all[df_taisho_all['部門コード名']==bumon_codename]
    file_name2 = bumon_codename + '.xlsx'
    file_path2 = os.path.join(dir_path,file_name2)
    df.to_excel(file_path2, sheet_name=bumon_codename)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?