工作中有时需要对 Excel 文件进行处理,如果文件比较多的话,人工处理比较费时间,可以使用 Python 代码提高处理效率。
读取 Excel 指定 Sheet 中的内容
使用 openpyxl 库对 Excel 文件处理,例如读取 Excel 文件中的 Sheet1 的内容生成数据库的 SQL 语句。
import os
import openpyxl
# 将待处理的所有文件放到此目录下
directory = '待处理的文件'
for file_name in os.listdir(directory):
file_path = os.path.join(directory, file_name)
workbook = openpyxl.load_workbook(file_path)
# 选择指定名称的工作表
sheet_name = 'Sheet1'
sheet = workbook[sheet_name]
sql = ''
# 按行读取数据,max_row指定最大的行数,max_col指定最大的列数,也可以通过min_row指定开始读取的行号
for row in sheet.iter_rows(max_row=8, max_col=4, values_only=True):
# 跳过标题行和序号列
if row[0] == '大标题' or row[0] == '序号':
continue
name, age, address = row
sql += (f"INSERT INTO table1 (name, age, address) VALUES('{name}','{age}','{address}');\n")
print(sql)
对原始内容进行处理
Excel 中的原始内容大部分有换行,如果生成 SQL 语句中不想有换行,可以把原始内容中的换行去掉,如果行结尾没有标点,中间的行结尾加上逗号,最后一行结尾加上句号。
def format_text(source):
if source is None:
return ''
# 去除首尾空白字符
cleaned_text = source.strip()
# 将文本按行分割
lines = cleaned_text.split('\n')
# 定义中文标点集合
chinese_punctuation = ('。', '!', '?', ';', ':', ',')
# 处理每一行,如果行尾没有标点,则加上逗号(除了最后一行)
for i in range(len(lines) - 1):
if not lines[i].endswith(chinese_punctuation):
lines[i] += ','
# 处理最后一行,如果行尾没有标点,则加上句号
last_line = lines[-1]
if not last_line.endswith(chinese_punctuation):
lines[-1] += '。'
# 连接所有行
processed_text = ''.join(lines)
return processed_text
删除 Excel 中指定 Sheet 外的其它 Sheet
如果只想保留 Excel 中的 Sheet1,其它 Sheet 要删除,可以使用如下代码:
import os
import openpyxl
# 将待处理的所有文件放到此目录下
directory = '待处理的文件'
for file_name in os.listdir(directory):
file_path = os.path.join(directory, file_name)
# 指定要保留的工作表名称
sheet_to_keep = 'Sheet1'
workbook = openpyxl.load_workbook(file_path)
# 获取所有工作表的名称
sheet_names = workbook.sheetnames
if sheet_to_keep not in sheet_names:
print(f"Warning: Sheet '{sheet_to_keep}' not found in {file_name}. Skipping this file.")
continue
# 遍历所有工作表,删除除了指定名称外的所有工作表
for sheet_name in sheet_names:
if sheet_name != sheet_to_keep:
del workbook[sheet_name]
workbook.save(file_path)
print(f"File {file_name} processed and saved with only the '{sheet_to_keep}' sheet.")
将文件批量上传到服务器上
使用 requests 库调用接口批量上传文件
import requests
import os
# 上传接口URL
url = 'https://xxx'
# 设置请求头,可以放入token等信息
headers = {
}
# 将待上传的所有文件放到此目录下
directory = '待上传的文件'
for file_name in os.listdir(directory):
file_path = os.path.join(directory, file_name)
# 使用with语句打开文件并构造multipart/form-data请求
with open(file_path, 'rb') as file:
# 构造form-data
files = {'file': file}
# 发送POST请求
response = requests.post(url, headers=headers, files=files)
# 检查响应状态码
if response.status_code == 200:
print(f'{file_name} upload successfully')
else:
print(f'Failed to upload file. Status code: {response.status_code}')
print(f'Response: {response.text}')
338

被折叠的 条评论
为什么被折叠?



