openpyxl,xlrd,win32com,wxpython,logging
一. openpyxl常用操作总结
官方文档: https://openpyxl.readthedocs.io/en/stable/tutorial.html
import openpyxl
def read_excel(filepath):
# 使用openpyxl.load_workbook()打开现有工作簿
wb = openpyxl.load_workbook(filepath, read_only=True)
ws = wb.active # 获取第一个sheet
row = ws.max_row # 获取最大行
col = ws.max_column # 获取最大列
li = []
for row in ws.iter_rows(min_row=2, max_row=row, min_col=1, max_col=col):
li2 = []
for cell in row:
li2.append(cell.value)
li.append((li2[5], li2[15], li2[16], li2[17])
dic = {}
for i in range(1, len(li)):
if li[i-1][0] == li[i][0]:
if not dic.get(li[i-1][0], ''):
dic.setdefault(li[i - 1][0], []).append(li[i-1])
dic[li[i][0]].append(li[i])
return dic
二. xlrd常用操作总结
import xlrd
def read_excel(filepath):
wb = xlrd.open_workbook(filepath)
ws = wb.sheet_by_index(0) # 获取第一个sheet
row = ws.nrows # 获取最大行
col = ws.ncols # 获取最大列
li = []
for rowx in range(1, row):
li2 = []
for colx in range(0, col):
li2.append(ws.cell_value(rowx, colx))
li.append((li2[5], li2[15], li2[16], li2[17]))
dic = {}
for i in range(1, len(li)):
if li[i - 1][0] == li[i][0]:
if not dic.get(li[i - 1][0], ''):
dic.setdefault(li[i - 1][0], []).append(li[i - 1])
dic[li[i][0]].append(li[i])
return dic
三. win32com常用操作总结
import os
import win32.client as win32
class ReadExcel:
def __init__(self, filepath):
self.xlApp = win32.gencache.EnsureDispatch('Excel.Application')
self.xlApp.Visible = 0
# self.xlApp.DisplayAlerts = 0
self.filename = filename
self.xlBook = self.xlApp.Workbooks.Open(filepath)
self.sheet = self.xlBook.Worksheets(1)
self.nrows = self.sheet.UsedRange.Rows.Count # 最大行
self.ncols = self.sheet.UsedRange.Columns.Count # 最大列
def close(self):
self.xlApp.Application.Quit()
def getCell(self, row, col):
return self.sheet.Cells(row, col).Value
def getRange(self, row1, col1, row2, col2):
return self.sheet.Range(self.sheet.Cells(row1, col1), self.sheet.Cells(row2, col2)).Value
def get_excel_value(filepath):
excel = ReadExcel(filepath)
li = []
for row in range(1, excel.nrows + 1):
tb_name = excel.getCell(row, 6)
field_en = excel.getCell(row, 16)
field_zh = excel.getCell(row, 17)
field_type = excel.getCell(row, 18)
li.append((tb_name, field_en, field_zh, field_type))
dic = {}
for i in range(1, len(li)):
if li[i - 1][0] == li[i][0]:
if not dic.get(li[i - 1][0], ''):
dic.setdefault(li[i - 1][0], []).append(li[i - 1])
dic[li[i][0]].append(li[i])
return dic
四. 自定义异常
class CustomException(Exception):
'''自定义异常'''
def __init__(self, msg):
Exception.__init__(self, msg)
self.msg = msg
五. 判断中文
def is_chinese(word):
for ch in word:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
六. Excel数字字母转换
def alpha2num(alpha):
if type(alpha) is not str:
return alpha
col = 0
power = 1
for i in range(len(alpha) - 1, -1, -1):
ch = alpha[i]
col += (ord(ch) - ord('A') + 1) * power
power *= 26
return col
def num2alpha(num):
if type(num) != int:
return num
num = num - 1
if num > 25:
ch1 = chr(num % 26 + 65)
ch2 = chr(num // 26 + 64)
return ch2 + ch1
else:
return chr(num % 26 + 65)
if __name__ == '__main__':
print(alpha2num('A'))
print(num2alpha(1))
七. 使用wxpython进行GUI编程
import wx
import os
from tools.converter import MyScript
wildcard = u"Excel文件 (*.xls)|*.xls|" \
u"Excel文件 (*.xlsx)|*.xlsx|" \
u"Excel文件 (*.xlsm)|*.xlsm|" \
u"Excel文件 (*.xltx)|*.xltx|" \
u"Excel文件 (*.xltm)|*.xltm|" \
u"Excel文件 (*.xlsb)|*.xlsb|" \
u"Excel文件 (*.xlam)|*.xlam"
class MyFileDialog(wx.Frame):
"""文件选择,保存"""
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, -1, 'xml转sql和sh', size=(600, 500))
self.filepath = ''
self.savepath = ''
wx.StaticText(self, -1, '接口单元:', (20, 25))
self.interface = wx.TextCtrl(self, pos=(75, 20))
self.btnChoose = wx.Button(self, -1, u"选择文件", (75, 100))
self.Bind(wx.EVT_BUTTON, self.OnBtnChoose, self.btnChoose)
self.btnSave = wx.Button(self, -1, u"保存文件", (75, 140))
self.Bind(wx.EVT_BUTTON, self.OnBtnSave, self.btnSave)
self.btnSubmit = wx.Button(self, -1, u"确认转换", (75, 180))
self.Bind(wx.EVT_BUTTON, self.OnBtnSubmit, self.btnSubmit)
def OnBtnChoose(self, event):
'''选择文件'''
dlg = wx.FileDialog(self, message=u"选择文件",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.FD_OPEN | wx.FD_MULTIPLE | wx.FD_CHANGE_DIR)
if dlg.ShowModal() == wx.ID_OK:
self.filepath = dlg.GetPath()
dlg.Destroy()
def OnBtnSave(self, event):
'''保存文件'''
dlg = wx.DirDialog(self, message=u"保存文件",
style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
self.savepath = dlg.GetPath()
dlg.Destroy()
def OnBtnSubmit(self, event):
'''确认转换'''
if not self.filepath:
msg = '请选择您要转换的文件'
dlg = ErrorDialog(None, -1, msg)
dlg.ShowModal()
dlg.Destroy()
if not self.savepath:
msg = '请选择保存路径'
dlg = ErrorDialog(None, -1, msg)
dlg.ShowModal()
dlg.Destroy()
if not self.interface.GetValue():
msg = '接口单元不能为空'
dlg = ErrorDialog(None, -1, msg)
dlg.ShowModal()
dlg.Destroy()
if self.filepath and self.savepath and self.interface.GetValue():
filepath = self.filepath
savepath = self.savepath
interface = self.interface.GetValue()
logger.info(f'interface: {interface}')
logger.info(f'filepath: {filepath}')
logger.info(f'savepath: {savepath}')
try:
script = MyScript(filepath, savepath, interface)
script.get_all_files()
dlg = ErrorDialog(None, -1, '转换成功!')
dlg.ShowModal()
dlg.Destroy()
except Exception as e:
logger.warning(str(e), exc_info=True)
dlg = ErrorDialog(None, -1, '出错了,请查看日志文件')
dlg.ShowModal()
dlg.Destroy()
class ErrorDialog(wx.Dialog):
def __init__(self, parent, id, msg):
super(ErrorDialog, self).__init__(parent, id, '提示信息', size=(600, 150))
self.app = wx.GetApp()
self.msg = msg
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(wx.StaticText(self, -1, self.msg), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, border=30)
self.sizer.Add(wx.Button(self, wx.ID_OK), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM, border=0)
self.SetSizer(self.sizer)
class App(wx.App):
def __init__(self):
wx.App.__init__(self)
def OnInit(self):
self.dialog = MyFileDialog()
self.dialog.Show(True)
return True
if __name__ == '__main__':
app = App()
app.MainLoop()
八. python日志配置
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# 注意: 在logger.xxx()中添加一个exc_info=True参数,就可以将错误信息写入日志文件中了
openpyxl,xlrd,win32com,wxpython,logging的更多相关文章
- 【问题解决方案】ImportError: No module named 'openpyxl'/‘xlrd’
背景: 在jupyter notebook to_excle: 运行将dataframe保存为excel文件 df.to_excel('dataframe.xlsx') 时报错openpyxl rea ...
- Python excel 库:Openpyxl xlrd 对比 介绍
打算用python做一个写mtk camera driver的自动化工具. 模板选用标准库里面string -> Template 即可 但要重定义替换字符,稍后说明 配置文件纠结几天:cfg, ...
- Python操作excel的几种方式--xlrd、xlwt、openpyxl
openpyxl xlrd xlwt 在处理excel数据时发现了xlwt的局限性–不能写入超过65535行.256列的数据(因为它只支持Excel 2003及之前的版本,在这些版本的Excel中 ...
- Python 读写操作Excel —— 安装第三方库(xlrd、xlwt、xlutils、openpyxl)
数据处理是 Python 的一大应用场景,而 Excel 则是最流行的数据处理软件.因此用 Python 进行数据相关的工作时,难免要和 Excel 打交道. 如果仅仅是要以表单形式保存数据,可以借助 ...
- Python操作excel(xlrd和xlwt)
Python操作excel表格有很多支持的库,例如:xlrd.xlwt.openpyxl.win32com,下面介绍使用xlrd.xlwt和xlutils模块这三个库不需要其他的支持,在任何操作系统上 ...
- Python处理Excel(转载)
1. Python 操作 Excel 的函数库 我主要尝试了 3 种读写 Excel 的方法: 1> xlrd, xlwt, xlutils: 这三个库的好处是不需要其它支持,在任何操作系统上都 ...
- Python在Office 365 开发中的应用
我在昨天发布的文章 -- 简明 Python 教程:人生苦短,快用Python -- 中提到了Python已经在Office 365开发中全面受支持,有不同朋友留言或私信说想了解更加详细的说明,所以特 ...
- Python 简单模块学习
1. openpyxl / xlrd / xlwt => 操作Excel 文件(xlsx格式) => xlrd + xlwt : 只能操作xls文件,分别负责读写, 暂时不讨论 => ...
- data cleaning
Cleaning data in Python Table of Contents Set up environments Data analysis packages in Python Cle ...
随机推荐
- DBA 有哪些工作
首先,我们看看DBA的工作有哪些?DBA的工作实际上都是围绕数据库展开,包含但不限于这些工作: 1. 数据库.主机.操作系统.交换机.存储选型,预算,架构设计,部署,参数优化: 2. 数据库备份.恢复 ...
- 机器学习实战(1)- KNN
KNN:k近邻算法-在训练样本中找到与待测样本距离相近的N个样本,并用这N个样本中所属概率最大的类别作为待测样本的类别. 算法步骤: 1.对训练中的样本数据的不同属性进行归一化处理. 2.计算待测样本 ...
- 洛谷P2751 工序安排Job Processing
题目 任务调度贪心. 需要明确一点,任务调度贪心题,并不是简单地应用排序的贪心,而是动态的运用堆,使每次选择是都能保持局部最优,并更新状态使得下次更新答案可以取到正确的最小值. 这是A过程的解. 然后 ...
- Pytest权威教程21-API参考-01-函数(Functions)
目录 函数(Functions) pytest.approx pytest.fail pytest.skip pytest.importorskip pytest.xfail pytest.exit ...
- Atcoder Grand Contest 026 (AGC026) F - Manju Game 博弈,动态规划
原文链接www.cnblogs.com/zhouzhendong/AGC026F.html 前言 太久没有发博客了,前来水一发. 题解 不妨设先手是 A,后手是 B.定义 \(i\) 为奇数时,\(a ...
- MySQL事务(脏读、不可重复读、幻读)
1. 什么是事务? 是数据库操作的最小工作单元,是作为单个逻辑工作单元执行的一系列操作:这些操作作为一个整体一起向系统提交,要么都执行.要么都不执行:事务是一组不可再分割的操作集合(工作逻辑单元): ...
- mysql5.6源码部署
一.准备环境 环境:centos-7.3 一台软件版本:mysql-5.6.39 1.安装依赖yum -y install autoconf libaio bison ncurses-devel 2. ...
- simplec与simple【转载】
转载自:http://blog.163.com/wu_yangfeng/blog/static/161897379201041581144971/ 在FLUENT中,可以使用标准SIMPLE算法和SI ...
- HTML Entity
1.1 介绍 在编写HTML页面时,需要用到"<".">"."空格"等符号,直接输入这些符号时,会错误的把它们与标记混在一起,非 ...
- DB2通过某列分组来去重
DB2通过某列分组来去重,可防止distinct对大字段的去重报错. row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组,在分 ...