1
0

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.

Windows 10 Pro + Python3 + OpenPyXL で CSVファイルを書き込んでみる

Last updated at Posted at 2019-02-03

#目的
Python3 + OpenPyXL で CSVファイルを Excel 2016 x86 に書き込んでみる
※VBAだと range = Variant() がデフォなんだけど
 Pythonだともう少し触ってみないとわかないなぁ・・・
対象データは郵便番号検索の17ISHIKA.CSV
##パッケージの追加
> pip3 install openpyxl
> pip3 install csv
##サンプルコード

#第1案---------------------------------------------
# CSV ファイルを Worksheet に書き込む
rows = 0
with open(csvfile, newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for line in spamreader:
        rows = rows + 1
        # print(line)
        cols = 0
        # 1行分のデータを書き込む
        # TODO 対象 Range の書式付け
        for col in line:
            cols = cols + 1
            wb[addsheet].cell(column=cols, row=rows).value = col
            # print(str(rows) + ":" + str(cols) + ":" + col)
#---------------------------------------------------

#第2案---------------------------------------------
# CSV ファイルを Worksheet に書き込む
ws = wb[addsheet]
with open(csvfile, newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for line in spamreader:
        ws.append(line)
#---------------------------------------------------

##参考にしたのは以下のサイト
openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files
Tutorial - openpyxl
csv — CSV File Reading and Writing
Python openpyxlでExcelを操作

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?