Linux openpyxl 将 CSV 转换为 EXCEL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12976378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
openpyxl convert CSV to EXCEL
提问by Satish
How can I convert a CSV file with :
delimiter to XLS (Excel sheet) using openpyxl
module?
如何:
使用openpyxl
模块将带分隔符的 CSV 文件转换为 XLS(Excel 工作表)?
采纳答案by John
Well here you go...
好吧,你去吧……
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)
回答by Adam Stewart
A much simpler, minimalist solution:
一个更简单、极简的解决方案:
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')
回答by Jaws
Here is Adam's solution expanded to strip out characters that openpyxl considers illegal and will throw an exception for:
以下是 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 is a compiled regular expression containing the characters openpyxl deems "illegal". The code is simply substituting those characters with an empty string.
ILLEGAL_CHARACTERS_RE 是一个已编译的正则表达式,其中包含 openpyxl 认为“非法”的字符。代码只是用空字符串替换这些字符。
Source: Bitbucket openpyxl issue #873 - Remove illegal characters instead of throwing an exception