马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
以下是将上述代码封装为函数的版本。函数汲取 input_excel_path、sheet_name 和 output_dbf_path 作为参数,按照需求读取 Excel 表格并导出为 DBF 文件。
封装函数代码
- import pandas as pd
- import dbf
- def excel_to_dbf(input_excel_path, sheet_name, output_dbf_path):
- """
- 将 Excel 的指定工作表导出为 DBF 文件,保留数据类型和列名格式。
- 参数:
- input_excel_path (str): 输入的 Excel 文件路径。
- sheet_name (str): 需要读取的工作表名称。
- output_dbf_path (str): 导出的 DBF 文件路径。
- """
- # 读取 Excel 的指定表
- df = pd.read_excel(input_excel_path, sheet_name=sheet_name)
- # 定义字段字符串列表,根据数据类型进行动态判断
- def get_field_definition(column):
- if df[column].dtype == 'object': # 字符类型
- return f"{column} C(255)"
- elif pd.api.types.is_integer_dtype(df[column]): # 整型
- return f"{column} N(10,0)" # 整型无需小数位,最大宽度10
- elif pd.api.types.is_float_dtype(df[column]): # 浮点型
- # 判断小数位数
- max_decimal_places = df[column].apply(
- lambda x: len(str(x).split(".")[1]) if pd.notnull(x) and "." in str(x) else 0
- ).max()
- return f"{column} N(18,{min(max_decimal_places, 5)})" # 浮点型设置小数位,限制最大5位
- elif pd.api.types.is_datetime64_any_dtype(df[column]): # 日期类型
- return f"{column} D"
- else:
- raise ValueError(f"Unsupported column type for {column}")
- # 生成字段定义,确保列名格式不变
- field_definitions = ";".join([get_field_definition(col) for col in df.columns])
- # 使用指定编码创建 DBF 表
- table = dbf.Table(output_dbf_path, field_definitions, codepage="utf8")
- table.open(dbf.READ_WRITE)
- # 写入数据
- for _, row in df.iterrows():
- row_data = tuple(row.fillna("").to_list()) # 用空值填充 NaN
- table.append(row_data)
- table.close()
- print(f"The table {sheet_name} exported to {output_dbf_path}.")
- # 使用示例
- if __name__ == "__main__":
- input_excel_path = r"E:\_OrderingProject\F_IslandsBoundaryChange\c_GeeData\Tif_Thumbnail_check\_check.xlsx"
- sheet_name = "fix_v1"
- output_dbf_path = r"E:\_OrderingProject\F_IslandsBoundaryChange\c_GeeData\Tif_Thumbnail_check\fix_v1.dbf"
-
- excel_to_dbf(input_excel_path, sheet_name, output_dbf_path)
复制代码 函数分析
- 函数参数:
- input_excel_path:输入的 Excel 文件路径。
- sheet_name:Excel 文件中须要导出的工作表名称。
- output_dbf_path:目标 DBF 文件的输出路径。
- 动态字段界说:
- 根据列数据范例(字符、整型、浮点型、日期等)天生得当的 DBF 字段界说。
- 确保小数位数动态调解(浮点型最多生存 5 位小数)。
- 自动添补缺失值:
- 用空字符串添补 NaN 值,确保写入 DBF 时不会堕落。
- 编码:
- 使用 utf8 编码创建 DBF 表,包管支持中笔墨符。
- 非常处置惩罚:
- 如果碰到不支持的数据范例,会引发 ValueError,提示用户查抄输入数据。
示例输出
假设输入的 fix_v1 工作表数据如下:
IDNameScoreDate1Alice95.02024-12-092Bob892024-12-083Carol82.52024-12-07导出的 fix_v1.dbf 文件会生存字段范例和格式同等。
如果这对您有所资助,渴望点赞支持一下作者! 😊
详细全文-点击检察
|