开头先对老板致以崇高的问候,问候他的十八辈。。。各种恩情难以言表,只能默默记在心里
开始老板没有给excel文件,自己试手用的是.xlsx文件,用的包是openpyxl包,读取毫无问题,
贴代码:
import os
import xlrd
from openpyxl import load_workbook
def xlsx_open():
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path_sx = os.path.join(base_dir, "files", "新建XLSX工作表.xlsx")
wb = load_workbook(file_path_sx)
sheet = wb.worksheets[0]
# for row in sheet.iter_rows(min_row=3, max_row=12):
# name = row[2].value
# data = row[3].value
# print(name, data)
# 遍历获取行列数
for row in sheet.iter_rows(min_row=2, max_row=2):
for low in row[0:]:
print(low.value)
if __name__ == "__main__":
# openpyxl只能读取xlsx文件格式的excel文件
xlsx_open()
事后,老板发了个.xls文件(甜蜜的),换成了xlrd包,贴代码:
import os
import sys
import xml.etree.ElementTree as ET
import xlrd
def xls_type(filename):
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path_s = os.path.join(base_dir, "files", filename)
file_path_s = file_path_s.encode(sys.getfilesystemencoding()) # 将文件夹名称转换为 Unicode 编码格式
print(file_path_s)
kb = xlrd.open_workbook(file_path_s)
sheet_s = kb.sheet_by_index(0)
# 读取数据
for row in range(sheet_s.nrows):
for col in range(sheet_s.ncols):
cell_value = sheet_s.cell_value(row, col)
print(cell_value)
if __name__ == "__main__":
# 文件不是正式的xls文件报(xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'<meta ht')错
# filename = "有问题的excel文件.xls"
# 将数据手动粘贴到新建的xls文件中解决
filename = "空气.xls"
xls_type(filename)
结果报错:xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'<meta ht',百度了一下,告诉我要不就是excel文件没有,要么就是excel文件损坏。检查了一下路径,发现确实能找到这个文件,所以排除没有excel文件,那就只剩下excel文件有问题了,果不其然,用电脑自带的excel软件打开显示文件后缀扩展名不对,右键文件用记事本打开发现是个标签文件(以为是xml文件,还有专门用了解析xml的,结果不是,后来仔细对照了一下表头标签发现和html文件的表头有点像)。
然后又去找了关于解析xml文件的代码,下载了pandas包,话不多说贴代码。
import os
import pandas as pd
base_dir = os.path.dirname(os.path.abspath(__file__))
# xml_name = "有问题的excel文件.xls"
xml_name = "有问题的excel文件转换过来的xml文件.xml"
file_path_x = os.path.join(base_dir, "files", xml_name)
# 获取表内所有数据
df = pd.read_xml(file_path_x, xpath='//td')
# 遍历是td标签的所有数据
td = df.td
for i in td:
# 遍历td标签里的值,不包含坐标
values = td.values
for i in values:
结果刚上来就报错了lxml.etree.XMLSyntaxError: Extra content at the end of the document, line 2, column 1,很明显的解析不了,文件的格式不对,那怎么办呢,甜蜜的,删了,直接改格式,不就是后期写个脚本改格式嘛,结果没想到文件里居然还有空格,直接一个 给我卡那了,意识到不对了,又重新看文件,发现还想html文件
然后就改成了html文件,下载beautifulsoup4包,贴代码:
import os
from bs4 import BeautifulSoup
xml_name = "有问题的转换成的html文件.html"
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path_x = os.path.join(base_dir, "files", xml_name)
with open(file_path_x, encoding='utf-8') as f:
soup = BeautifulSoup(f.read(), 'html.parser')
# # 获取html页面的顶级标签
# for child in soup.children:
# print(child)
# 再遍历获取tr标签内的所有数据
for row in soup.find_all('tr'):
print(row)
文本转换(将xls文件转换成html文件)
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path_sx = os.path.join(base_dir, "files")
# file_path_sx = os.path.join(file_path_sx, "新建XLS文件.xls")
for filename in os.listdir(file_path_sx):
if filename.endswith(".xls"):
new_filename = os.path.splitext(filename)[0] + ".xml" # 生成新的文件名
old_file_path = os.path.join(file_path_sx, filename) # 原文件路径
new_file_path = os.path.join(file_path_sx, new_filename) # 新文件路径
os.rename(old_file_path, new_file_path) # 重命名文件
贴一个转成的xls文件的代码格式:
<meta http-equiv="content-type" content="application/ms-excel; charset=UTF-8"/>
<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
<tr>
<td align="center" colspan="9" style="font-size:20pt;font-weight:bold;">标题</td>
</tr>
<tr>
<td align="center" style="width:130px;">日期</td>
<td align="center" style="width:130px;">城市</td>
<td align="center" style="width:130px;"> </td>
</tr>
....
</table>
这才算告一段落,当然也主要是自己对python不熟悉以及文本转换excel导致的,虚心学习,干掉老板,甜蜜的