python:创建excel工作簿和转储csv文件作为工作表 [英] python: creating excel workbook and dumping csv files as worksheets
问题描述
我有很少的csv文件,我想转储为一个excel工作簿(xls / xlsx)的新工作表。
如何实现这一点?
I have few csv files which I would like to dump as new worksheets in a excel workbook(xls/xlsx). How do I achieve this?
Googled发现了pyXLwriter,但似乎项目已停止。
虽然我试着'pyXLwriter'想知道有什么替代/建议/模块吗?
Googled and found 'pyXLwriter' but it seems the project was stopped. While Im trying out 'pyXLwriter' would like to know are there any alternatives/suggestions/modules?
很感谢。
这里是我的解决方案:(任何人都有更精简,更多的pythonic解决方案? b
$ b
Here is my solution: (anyone has much leaner, much pythonic solution? do comment. thx)
import glob
import csv
import xlwt
import os
wb = xlwt.Workbook()
for filename in glob.glob("c:/xxx/*.csv"):
(f_path, f_name) = os.path.split(filename)
(f_short_name, f_extension) = os.path.splitext(f_name)
ws = wb.add_sheet(str(f_short_name))
spamReader = csv.reader(open(filename, 'rb'), delimiter=',',quotechar='"')
row_count = 0
for row in spamReader:
for col in range(len(row)):
ws.write(row_count,col,row[col])
row_count +=1
wb.save("c:/xxx/compiled.xls")
print "Done"
推荐答案
的意思是更精简,更多的pythonic,但你肯定可以spruce它一点:
Not sure what you mean by "much leaner, much pythonic" but you certainly could spruce it up a bit:
import glob, csv, xlwt, os
wb = xlwt.Workbook()
for filename in glob.glob("c:/xxx/*.csv"):
(f_path, f_name) = os.path.split(filename)
(f_short_name, f_extension) = os.path.splitext(f_name)
ws = wb.add_sheet(f_short_name)
spamReader = csv.reader(open(filename, 'rb'))
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
ws.write(rowx, colx, value)
wb.save("c:/xxx/compiled.xls")
这篇关于python:创建excel工作簿和转储csv文件作为工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!