python:创建excel工作簿并将csv文件转储为工作表

时间:2011-04-18 15:56:08

标签: python excel csv xlrd xlwt

我有几个csv文件,我想在excel工作簿(xls / xlsx)中作为新工作表转储。 我如何实现这一目标?

用Google搜索并发现'pyXLwriter',但似乎该项目已停止。 虽然我试着'pyXLwriter'想知道有没有其他选择/建议/模块?

非常感谢。

[编辑]

这是我的解决方案:(任何人都有更精简,更多的pythonic解决方案?做评论.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"

6 个答案:

答案 0 :(得分:28)

不确定是什么意思“更精简,更py”但你肯定可以稍微修饰一下:

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")

答案 1 :(得分:12)

您可以在xlwt tutorial中找到所需的一切。这些库(xlrd and xlwt)是在Python中管理Excel交互的最常用选择。缺点是,目前它们只支持Excel二进制格式(.xls)。

答案 2 :(得分:3)

我总是通过字符串编写Office 2003 XML格式。它比编写和压缩构成xlsx文档的内容更容易管理和管理。它也不需要任何外部库。 (虽然人们可以很容易地自己动手)

此外,Excel支持加载CSV文件。空格分隔或字符分隔。您可以直接加载,也可以尝试复制&粘贴它,然后按选项中的文本到列按钮。当然,这个选项与python无关。

答案 3 :(得分:3)

也可在GitHub repo“Kampfmitexcel”中找到......

import csv, xlwt, os

def input_from_user(prompt):
    return raw_input(prompt).strip()

def make_an_excel_file_from_all_the_txtfiles_in_the_following_directory(directory):
    wb = xlwt.Workbook()
    for filename in os.listdir(data_folder_path):
        if filename.endswith(".csv") or filename.endswith(".txt"):
            ws = wb.add_sheet(os.path.splitext(filename)[0])
            with open('{}\\{}'.format(data_folder_path,filename),'rb') as csvfile:
                reader = csv.reader(csvfile, delimiter=',')
                for rowx, row in enumerate(reader):
                    for colx, value in enumerate(row):
                        ws.write(rowx, colx, value)
    return wb

if __name__ == '__main__':
    path_to_data = input_from_user("Where is the data stored?: ")
    xls = make_an_excel_file_from_all_the_txtfiles_in_the_following_directory(path_to_data)
    xls_name = input_from_user('What do you want to name the excel file?: ')
    xls.save('{}\\{}{}'.format(data_folder_path,xls_name,'.xls'))
    print "Your file has been saved in the data folder."

答案 4 :(得分:3)

使用xlsxwriter在python中创建和写入excel文件。

安装:pip install xlsxwriter

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

答案 5 :(得分:1)

这是基于答案本身的答案。但我使用xlsxwriter的原因是因为它接受了xlsx格式的更多数据。其中xlwt将您限制为65556行和xls格式。

import xlsxwriter
import glob
import csv
workbook = xlsxwriter.Workbook('compiled.xlsx') 
for filename in glob.glob("*.csv"):
    ws = workbook.add_worksheet(str(filename.split('.')[0]))
    spamReader = csv.reader(open(filename, 'rb'), delimiter=',',quotechar='"')
    row_count = 0
    print filename
    for row in spamReader:
        for col in range(len(row)):
            ws.write(row_count,col,row[col])
        row_count +=1

workbook.close()