LoginSignup
8
6

More than 5 years have passed since last update.

pythonでデータ書き出しの際に「openpyxl.utils.exceptions.IllegalCharacterError」が出たときの対応

Posted at

pandasを使用してデータをサーバから取得し、openpyxlを使用してデータをExcelなどに書き出す場合に下記のエラーが出る場合がある。

openpyxl.utils.exceptions.IllegalCharacterError

理由としては取得したデータフレームの中にopenxmlで扱えない不正な文字が含まれている、ということなので下記のように除外するための関数を1回挟めばOK

import pandas as pd
import openpyxl

def illegal_char_remover(data):
    ILLEGAL_CHARACTERS_RE = re.compile(
        r'[\000-\010]|[\013-\014]|[\016-\037]|[\x00-\x1f\x7f-\x9f]|[\uffff]')
    """Remove ILLEGAL CHARACTER."""
    if isinstance(data, str):
        return ILLEGAL_CHARACTERS_RE.sub("", data)
    else:
        return data

#サーバ情報
conn = pyodbc.connect(サーバ情報)
#クエリ実行
df = pd.read_sql(クエリ情報, conn )
#IllegalCharacter除外(ここが追加分)
df = df.applymap(illegal_char_remover)

8
6
1

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
8
6