LoginSignup
1
0

More than 1 year has passed since last update.

(xlwing使用)空白があるテキストファイル(数行)を読み込んで、excelに貼り付ける mshmura

Last updated at Posted at 2020-11-28

xlwing 使用

テキストファイルの中身

test.txt
テスト test      t3    USD   44
te  55   99     gbe   99

pythonファイル

hello.py

def import_txt_split():

    # ブックの読み込み
    wb = xw.Book.caller()

    # シートの読み込み
    sht = wb.sheets['Sheet1']

    # テキストファイルの読み込み
    f = open('test.txt', 'r',encoding='UTF-8')

    # 各行をリストで取得
    datalist = f.readlines()

    # 空白を取り除く
    s = [i.split() for i in datalist]

    # 1行ずつ、リストをペッと貼り付ける
    for num,i in enumerate(s):
        sht.cells(num+1,1).value = i

    # テキストファイルを閉じる
    f.close()

VBA側

Sub import_text()
    RunPython ("import hello; hello.import_txt_split()")
End Sub

このVBAをボタンにマクロ登録。クリック

結果

qita1.png

上記の方法以外に、pandasのdataframeに貼り付けて、A1セルにぺっと貼り付ける方法でも出来た

1
0
2

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
0