简体   繁体   English

.DBF转换为.csv时出现BadDataError

[英]BadDataError when converting .DBF to .csv

I am trying to convert a .DBF file to .csv using Python3. 我正在尝试使用Python3将.DBF文件转换为.csv。 I am trying using the dbf library ( https://pypi.python.org/pypi/dbf ) 我正在尝试使用dbf库( https://pypi.python.org/pypi/dbf

import dbf 

def dbf_to_csv(dbf_file_name, csv_file_name):
    dbf_file = dbf.Table(dbf_file_name, ignore_memos=True)
    dbf_file.open() 
    dbf.export(dbf_file, filename = csv_file_name, format='csv', header=True)

The DBF file I am using can be opened in Excel and appears to be fine. 可以在Excel中打开我正在使用的DBF文件,看起来不错。 However, when I run the above method I get an error on the dbf.export line above: 但是,当我运行上述方法时,在上面的dbf.export行上出现错误:

dbf.ver_33.BadDataError: record data is not the correct length (should be 1442, not 1438)

The dbf file opens fine in Excel, however, I need to automate this conversion. dbf文件可以在Excel中正常打开,但是,我需要自动执行此转换。 What should I be doing differently to get this method to create a pdf from a .DBF file? 为了使此方法从.DBF文件创建pdf,我应该做些什么?

If the file is opening correctly in Excel, then I suggest you use Excel to do the conversion for you to csv format as follows: 如果该文件已在Excel中正确打开,则建议您使用Excel如下进行转换为csv格式:

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(r"input.dbf")
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(r"output.csv", FileFormat=6, ConflictResolution=2)
excel.Application.Quit()

Do not forget to add full paths to the required files. 不要忘记将完整路径添加到所需文件。 Note, FileFormat=6 tells Excel to save the file in CSV format. 注意, FileFormat=6告诉Excel将文件保存为CSV格式。

To export the workbook as a PDF, you could use: 要将工作簿导出为PDF,可以使用:

wb.ExportAsFixedFormat(0, r"output.pdf")

If you do not already have win32com installed you should be able to use the following: 如果尚未安装win32com ,则应该可以使用以下软件:

pip install pypiwin32

This solution is suitable for Windows installations only. 此解决方案仅适用于Windows安装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM