Tablib导出损坏文件

2024-04-18 22:04:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的代码,用python上的Tablib将csv转换回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无法读取编码数据?在


Tags: csv代码importreaddbdataopenutf8
3条回答

如果您使用的是新的openpyxl2.5,这将不起作用。您需要删除2.5,而不是pip安装2.4.9。在

    import tablib

根据它是数据集(一页)还是数据集(多页),您需要声明:(此处更改)

^{pr2}$

或者

    imported_data = tablib.Databook()

然后您就可以导入数据了

    imported_data.csv = tablib.import_set(open('DB.csv', enconding='utf8').read())

如果不在示例中指定.csv,tablib就不知道格式。在

    imported_data = tablib.import_set(open('DB.csv',encoding='utf8').read())

然后您可以打印查看您的各种选项。在

    print(imported_data)
    print(imported_data.csv)
    print(imported_data.xlsx)
    print(imported_data.dict)
    print(imported_data.db)

等等

然后写下你的文件

    f = open('workfile.xls', 'wb')
    f.write(imported_data.xls)  # or .xlsx
    f.close()

这两个函数允许您在导出到excel文件后从csv导入

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)

另一种方法是,您可以要求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有一个可以使用的File formats列表,其中56用于xls。在

相关问题 更多 >