10

如何:使用模块将带分隔符的 CSV 文件转换为 XLS(Excel 工作表)openpyxl

4

4 回答 4

63

一个更简单,极简的解决方案:

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('file.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')
于 2016-09-04T13:30:58.373 回答
17
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

f = open(r'C:\Users\Asus\Desktop\herp.csv')

csv.register_dialect('colons', delimiter=':')

reader = csv.reader(f, dialect='colons')

wb = Workbook()
dest_filename = r"C:\Users\Asus\Desktop\herp.xlsx"

ws = wb.worksheets[0]
ws.title = "A Snazzy Title"

for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = get_column_letter((column_index + 1))
        ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell

wb.save(filename = dest_filename)
于 2012-10-22T17:23:58.713 回答
2

这是 Adam 的解决方案,扩展后删除了 openpyxl 认为非法的字符,并将抛出异常:

import re
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
...
##ws.append(row) - Replace with the code below
for i in row:
    ws.append([ILLEGAL_CHARACTERS_RE.sub('',i)])

ILLEGAL_CHARACTERS_RE 是一个编译的正则表达式,包含 openpyxl 认为“非法”的字符。该代码只是用空字符串替换这些字符。

来源:Bitbucket openpyxl issue #873 - 删除非法字符而不是抛出异常

于 2018-06-12T20:53:37.427 回答
0

在 John 的建议之上,我使用函数稍微修改了我的脚本,以删除所有原始数据的字符串撇号。这样,我设法检查了所有原始数据(字符串和数字),它们也放置在相应的单元格中。最后,我从第 20 行开始将数值数据分配给浮点类型。这是因为所有数字数据从第 20 行开始就存在,而上面的所有数据都只是文本。

cell_value = cell.replace('"', '')

下面是我的脚本:

import csv
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

with open(filepath1_csv) as f:
reader = csv.reader(f)
for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = column_index + 1
        cell_value = cell.replace('"', '')
        ws.cell(row = row_index + 1, column = column_letter).value = cell_value

for row in ws.iter_rows(min_row=20, min_col=1, max_col=5, 
max_row=ws.max_row):
for cell in row:
    if cell.value is None:
        break
    else:
        cell.value = float(cell.value)

wb.save(filename = filepath1_xlsx)   
于 2021-06-15T06:48:29.090 回答