LoginSignup
12
13

More than 5 years have passed since last update.

PythonでCSVデータをExcelに貼り付ける際のスタイリッシュ技

Last updated at Posted at 2016-02-14

やりたいこと

PythonでCSVデータ取得、整形、Excel貼り付け
そんなシチュエーションないと思いますが不幸にも僕はあったので。


2016/02/14 追記
ウルトラスタイリッシュ技をコメントに@okadate さんが残してくださいました。
そちらをご参照ください。
以降は、深夜テンションで作り上げてしまった残骸となります。


環境

Windows7
Python3.4

こういうCSVデータをこう貼り付けたい

sample.csv
 ,Label,Area,Mean,Min,Max
1,4mas.tif,40000,0.000,0,0
2,10mas.tif,40000,32757.335,30635,34880
3,25mas.tif,40000,32784.505,1039,64761
4,40mas.tif,40000,32836.377,1371,65157

上記CSVをコピーしてExcelに値貼り付けすると
jg.PNG
こうなってしまう。

理想はこう
gjapo.PNG

私はこうした

sample.py
import win32com.client as win32
xlApp = win32.Dispatch("Excel.Application")
xlApp.Visible = 1
wb = xlApp.Workbooks.Open("C:/Users/user/Documents/1.xls")
Sheet = xlApp.Workbooks(1).Sheets(1)
f=open("C:/Users/user/Documents/sample.csv",'r')
for i,line in enumerate(f.readlines()):#ここがミソ
    for n,label in enumerate(line.split(",")):
        cell = Sheet.Cells(i+1,n+1)#win32では1からCellを開始する為
        cell.Value = label

そこがミソです。
enumerateはインデックスとともにループするので、それに+1してCellに合わせてます。
Pythonっぽい書き方ですね(言いたいだけ)

手でやったら一瞬なのですがPythonでやりたかったんです。
(夜中に思いついたのでなにか重要な事を見落としてる気がする)

他にいい方法ありましたら教えて下さい

問題

問題が。。。
hgap.PNG
勝手に「折り返して全体を表示」とかになってしまう。
ダサい。

12
13
3

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
12
13