我怎么能转换一个CSV文件:
使用分隔符为XLS(Excel工作表) openpyxl
模块?
Answer 1:
那么这里你去...
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)
Answer 2:
一个更简单,简约的解决方案:
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')
Answer 3:
这是亚当的解决方案扩展到去掉那个openpyxl认为非法的,将抛出一个异常的特点:
import re
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
...
##ws.append(row) - Replace with the code below
ws.append([ILLEGAL_CHARACTERS_RE.sub('',row)])
ILLEGAL_CHARACTERS_RE是包含openpyxl认为“非法”的字符的正则表达式编译。 该代码是简单地用一个空字符串代替这些字符。
来源: 到位桶openpyxl问题#873 -删除非法字符,而不是抛出一个异常
文章来源: openpyxl convert CSV to EXCEL