Tablib导出损坏的文件

我正在写一个简单的代码来将python上的csv与Tablib转换回xls。

据我所知,如果您导入csv,Tablib会为您进行转换。

import tablib imported_data = tablib.import_set(open('DB.csv',encoding='utf8').read()) f = open('workfile.xls', 'wb') f.write(imported_data.xls) f.close() 

此代码处理数据库的小样本,但在一个点(~600行)失败,这意味着编译成功,但Excel无法打开该文件。

我不知道如何继续 – 这个tablib失败或Excel不能读取编码的数据?

作为一种替代方法,您可以让Excel按照以下方式进行转换:

 import win32com.client as win32 import os excel = win32.gencache.EnsureDispatch('Excel.Application') src_filename = r"c:\my_folder\my_file.csv" name, ext = os.path.splitext(src_filename) target_filename = name + '.xls' wb = excel.Workbooks.Open(src_filename) excel.DisplayAlerts = False wb.DoNotPromptForConvert = True wb.CheckCompatibility = False wb.SaveAs(target_filename, FileFormat=56, ConflictResolution=2) excel.Application.Quit() 

Microsoft有一个您可以使用的文件格式列表,其中56用于xls

这两个函数允许你从csv导入后导出为ex​​cel文件

 import csv from xlsxwriter import Workbook import operator # This function for import from csv def CSV2list_dict(file_name): with open(file_name) as f: a = [{k: int(v) for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] return a # file_name must be end with .xlsx # The second parameter represente the header row of data in excel, # The type of header is a list of string, # The third paramater represente the data in list dictionaries form # The last paramater represente the order of the key def Export2excel(file_name, header_row, list_dict, order_by): list_dict.sort(key=operator.itemgetter(order_by)) wb=Workbook(file_name) ws=wb.add_worksheet("New Sheet") #or leave it blank, default name is "Sheet 1" first_row=0 for header in header_row: col=header_row.index(header) # we are keeping order. ws.write(first_row,col,header) # we have written first row which is the header of worksheet also. row=1 for art in list_dict: for _key,_value in art.items(): col=header_row.index(_key) ws.write(row,col,_value) row+=1 #enter the next row wb.close() csv_data = CSV2list_dict('DB.csv') header = ['col0','col1','col2'] order = 'col0' # the type of col0 is int Export2excel('workfile.xlsx', header, csv_data, order)