Skip to content

Commit

Permalink
拼接字符串
Browse files Browse the repository at this point in the history
  • Loading branch information
gxcuizy committed Sep 24, 2021
1 parent b607d93 commit 72167d1
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
3 changes: 2 additions & 1 deletion 拼接表格单行数据为字符串/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
### 文件结构

```
├── join_excel_data.py # 拼接Excel表格单行数据
├── join_excel.py # 拼接Excel表格单行数据(不用引号拼接)
├── join_excel_data.py # 拼接Excel表格单行数据(需要引号拼接)
```

### 功能描述
Expand Down
67 changes: 67 additions & 0 deletions 拼接表格单行数据为字符串/join_excel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
拼接Excel表格单行数据,并写入文本
author: gxcuizy
time: 2021-09-24
"""

import pandas
import os
import time


def print_msg(msg=''):
"""打印信息"""
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('[' + now_time + '] ' + msg)


# 程序主入口
if __name__ == "__main__":
# 获取传入参数
file_input = input('请输入当前目录下的表格文件名(默认“file”):') or 'file'
line_num = input('请输入要拼装的数据第几列(默认“1”):') or '1'
# 判断文件是否存在
file_name = str(file_input) + '.xlsx'
if os.path.exists(file_name) == False:
file_name = str(file_input) + '.xls'
if os.path.exists(file_name) == False:

print_msg('文件不存在')
os.system("pause")
exit(0)
# 判断输入的行数是否为数字
if line_num.isdigit() == False:
print_msg('请输入列数的数字')
os.system("pause")
exit(0)
try:
# 获取表格数据
print_msg('开始获取文件[' + file_name + ']的第[' + str(line_num) + ']列数据')
line_num = int(line_num) - 1
sheet = pandas.read_excel(io=file_name, usecols=[line_num], header=None)
data = sheet.values.tolist()
str_data = ''
# 循环处理数据
print_msg('已获取列数据条数[' + str(len(data)) + '],开始处理数据……')
for x in range(len(data)):
if str(data[x][0]) != 'nan':
# 自动切割最后一个字符串
row_val = str(data[x][0])
row_list = row_val.split('/')
row_len = len(row_list)
row_key = row_len - 1
str_data += str(row_list[row_key]) + ","
# 写入文本文件
print_msg('数据处理完毕,开始写入……')
log_name = 'str.txt'
with open(log_name, 'w') as f:
f.write(str_data.strip(','))
print_msg('数据文件[' + log_name + ']写入完毕,请打开查看.')
except Exception as err_info:
# 异常信息
print_msg(str(err_info))
# 防止exe程序执行结束闪退
os.system("pause")
Binary file not shown.

0 comments on commit 72167d1

Please sign in to comment.