在this post中有一个Python示例,可以从csv转换为xls。
但是,我的文件有超过65536行,所以xls不起作用。如果我将文件命名为xlsx,它并没有什么区别。是否有Python包转换为xlsx?
答案 0 :(得分:60)
以下是使用xlsxwriter的示例:
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
仅供参考,还有一个名为openpyxl的软件包,可以读/写Excel 2007 xlsx / xlsm文件。
希望有所帮助。
答案 1 :(得分:25)
使用我的库pyexcel
,
$ pip install pyexcel pyexcel-xlsx
您可以在一个命令行中执行此操作:
from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2
import glob
merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")
每个csv都有自己的工作表,名称将是他们的文件名。
答案 2 :(得分:6)
添加专门使用pandas库读取.csv文件的答案并另存为.xlsx文件。此示例使用pandas.read_csv
(Link to docs)和pandas.dataframe.to_excel
(Link to docs)。
完全可重现的示例使用numpy仅生成随机数,如果您想使用自己的.csv文件,可以将其删除。
import pandas as pd
import numpy as np
# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)
# Reading in test.csv and saving as test.xlsx
df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()
答案 3 :(得分:5)
from openpyxl import Workbook
import csv
wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
for row in csv.reader(f):
ws.append(row)
wb.save('name.xlsx')
答案 4 :(得分:4)
我如何使用 openpyxl lib:
import csv
from openpyxl import Workbook
def convert_csv_to_xlsx(self):
wb = Workbook()
sheet = wb.active
CSV_SEPARATOR = "#"
with open("my_file.csv") as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
for idx, val in enumerate(col.split(CSV_SEPARATOR)):
cell = sheet.cell(row=r+1, column=idx+1)
cell.value = val
wb.save("my_file.xlsx")
答案 5 :(得分:3)
简单的1对1 CSV到XLSX文件转换,而无需枚举/循环遍历这些行:
import pyexcel
sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")
sheet.save_as("myFile.xlsx")
注意:
答案 6 :(得分:0)
有一种简单的方法
inputStyles: [{
fontFamily: 'Roboto',
}],
// more initialization parameters
答案 7 :(得分:0)
使用熊猫的简单两行代码解决方案
import pandas as pd
read_file = pd.read_csv ('File name.csv')
read_file.to_excel ('File name.xlsx', index = None, header=True)