一. openpyxl常用操作总结

官方文档: https://openpyxl.readthedocs.io/en/stable/tutorial.html

  1. import openpyxl
  2. def read_excel(filepath):
  3. # 使用openpyxl.load_workbook()打开现有工作簿
  4. wb = openpyxl.load_workbook(filepath, read_only=True)
  5. ws = wb.active # 获取第一个sheet
  6. row = ws.max_row # 获取最大行
  7. col = ws.max_column # 获取最大列
  8. li = []
  9. for row in ws.iter_rows(min_row=2, max_row=row, min_col=1, max_col=col):
  10. li2 = []
  11. for cell in row:
  12. li2.append(cell.value)
  13. li.append((li2[5], li2[15], li2[16], li2[17])
  14. dic = {}
  15. for i in range(1, len(li)):
  16. if li[i-1][0] == li[i][0]:
  17. if not dic.get(li[i-1][0], ''):
  18. dic.setdefault(li[i - 1][0], []).append(li[i-1])
  19. dic[li[i][0]].append(li[i])
  20. return dic

二. xlrd常用操作总结

  1. import xlrd
  2. def read_excel(filepath):
  3. wb = xlrd.open_workbook(filepath)
  4. ws = wb.sheet_by_index(0) # 获取第一个sheet
  5. row = ws.nrows # 获取最大行
  6. col = ws.ncols # 获取最大列
  7. li = []
  8. for rowx in range(1, row):
  9. li2 = []
  10. for colx in range(0, col):
  11. li2.append(ws.cell_value(rowx, colx))
  12. li.append((li2[5], li2[15], li2[16], li2[17]))
  13. dic = {}
  14. for i in range(1, len(li)):
  15. if li[i - 1][0] == li[i][0]:
  16. if not dic.get(li[i - 1][0], ''):
  17. dic.setdefault(li[i - 1][0], []).append(li[i - 1])
  18. dic[li[i][0]].append(li[i])
  19. return dic

三. win32com常用操作总结

  1. import os
  2. import win32.client as win32
  3. class ReadExcel:
  4. def __init__(self, filepath):
  5. self.xlApp = win32.gencache.EnsureDispatch('Excel.Application')
  6. self.xlApp.Visible = 0
  7. # self.xlApp.DisplayAlerts = 0
  8. self.filename = filename
  9. self.xlBook = self.xlApp.Workbooks.Open(filepath)
  10. self.sheet = self.xlBook.Worksheets(1)
  11. self.nrows = self.sheet.UsedRange.Rows.Count # 最大行
  12. self.ncols = self.sheet.UsedRange.Columns.Count # 最大列
  13. def close(self):
  14. self.xlApp.Application.Quit()
  15. def getCell(self, row, col):
  16. return self.sheet.Cells(row, col).Value
  17. def getRange(self, row1, col1, row2, col2):
  18. return self.sheet.Range(self.sheet.Cells(row1, col1), self.sheet.Cells(row2, col2)).Value
  19. def get_excel_value(filepath):
  20. excel = ReadExcel(filepath)
  21. li = []
  22. for row in range(1, excel.nrows + 1):
  23. tb_name = excel.getCell(row, 6)
  24. field_en = excel.getCell(row, 16)
  25. field_zh = excel.getCell(row, 17)
  26. field_type = excel.getCell(row, 18)
  27. li.append((tb_name, field_en, field_zh, field_type))
  28. dic = {}
  29. for i in range(1, len(li)):
  30. if li[i - 1][0] == li[i][0]:
  31. if not dic.get(li[i - 1][0], ''):
  32. dic.setdefault(li[i - 1][0], []).append(li[i - 1])
  33. dic[li[i][0]].append(li[i])
  34. return dic

四. 自定义异常

  1. class CustomException(Exception):
  2. '''自定义异常'''
  3. def __init__(self, msg):
  4. Exception.__init__(self, msg)
  5. self.msg = msg

五. 判断中文

  1. def is_chinese(word):
  2. for ch in word:
  3. if '\u4e00' <= ch <= '\u9fff':
  4. return True
  5. return False

六. Excel数字字母转换

  1. def alpha2num(alpha):
  2. if type(alpha) is not str:
  3. return alpha
  4. col = 0
  5. power = 1
  6. for i in range(len(alpha) - 1, -1, -1):
  7. ch = alpha[i]
  8. col += (ord(ch) - ord('A') + 1) * power
  9. power *= 26
  10. return col
  11. def num2alpha(num):
  12. if type(num) != int:
  13. return num
  14. num = num - 1
  15. if num > 25:
  16. ch1 = chr(num % 26 + 65)
  17. ch2 = chr(num // 26 + 64)
  18. return ch2 + ch1
  19. else:
  20. return chr(num % 26 + 65)
  21. if __name__ == '__main__':
  22. print(alpha2num('A'))
  23. print(num2alpha(1))

七. 使用wxpython进行GUI编程

  1. import wx
  2. import os
  3. from tools.converter import MyScript
  4. wildcard = u"Excel文件 (*.xls)|*.xls|" \
  5. u"Excel文件 (*.xlsx)|*.xlsx|" \
  6. u"Excel文件 (*.xlsm)|*.xlsm|" \
  7. u"Excel文件 (*.xltx)|*.xltx|" \
  8. u"Excel文件 (*.xltm)|*.xltm|" \
  9. u"Excel文件 (*.xlsb)|*.xlsb|" \
  10. u"Excel文件 (*.xlam)|*.xlam"
  11. class MyFileDialog(wx.Frame):
  12. """文件选择,保存"""
  13. # ----------------------------------------------------------------------
  14. def __init__(self):
  15. """Constructor"""
  16. wx.Frame.__init__(self, None, -1, 'xml转sql和sh', size=(600, 500))
  17. self.filepath = ''
  18. self.savepath = ''
  19. wx.StaticText(self, -1, '接口单元:', (20, 25))
  20. self.interface = wx.TextCtrl(self, pos=(75, 20))
  21. self.btnChoose = wx.Button(self, -1, u"选择文件", (75, 100))
  22. self.Bind(wx.EVT_BUTTON, self.OnBtnChoose, self.btnChoose)
  23. self.btnSave = wx.Button(self, -1, u"保存文件", (75, 140))
  24. self.Bind(wx.EVT_BUTTON, self.OnBtnSave, self.btnSave)
  25. self.btnSubmit = wx.Button(self, -1, u"确认转换", (75, 180))
  26. self.Bind(wx.EVT_BUTTON, self.OnBtnSubmit, self.btnSubmit)
  27. def OnBtnChoose(self, event):
  28. '''选择文件'''
  29. dlg = wx.FileDialog(self, message=u"选择文件",
  30. defaultDir=os.getcwd(),
  31. defaultFile="",
  32. wildcard=wildcard,
  33. style=wx.FD_OPEN | wx.FD_MULTIPLE | wx.FD_CHANGE_DIR)
  34. if dlg.ShowModal() == wx.ID_OK:
  35. self.filepath = dlg.GetPath()
  36. dlg.Destroy()
  37. def OnBtnSave(self, event):
  38. '''保存文件'''
  39. dlg = wx.DirDialog(self, message=u"保存文件",
  40. style=wx.DD_DEFAULT_STYLE)
  41. if dlg.ShowModal() == wx.ID_OK:
  42. self.savepath = dlg.GetPath()
  43. dlg.Destroy()
  44. def OnBtnSubmit(self, event):
  45. '''确认转换'''
  46. if not self.filepath:
  47. msg = '请选择您要转换的文件'
  48. dlg = ErrorDialog(None, -1, msg)
  49. dlg.ShowModal()
  50. dlg.Destroy()
  51. if not self.savepath:
  52. msg = '请选择保存路径'
  53. dlg = ErrorDialog(None, -1, msg)
  54. dlg.ShowModal()
  55. dlg.Destroy()
  56. if not self.interface.GetValue():
  57. msg = '接口单元不能为空'
  58. dlg = ErrorDialog(None, -1, msg)
  59. dlg.ShowModal()
  60. dlg.Destroy()
  61. if self.filepath and self.savepath and self.interface.GetValue():
  62. filepath = self.filepath
  63. savepath = self.savepath
  64. interface = self.interface.GetValue()
  65. logger.info(f'interface: {interface}')
  66. logger.info(f'filepath: {filepath}')
  67. logger.info(f'savepath: {savepath}')
  68. try:
  69. script = MyScript(filepath, savepath, interface)
  70. script.get_all_files()
  71. dlg = ErrorDialog(None, -1, '转换成功!')
  72. dlg.ShowModal()
  73. dlg.Destroy()
  74. except Exception as e:
  75. logger.warning(str(e), exc_info=True)
  76. dlg = ErrorDialog(None, -1, '出错了,请查看日志文件')
  77. dlg.ShowModal()
  78. dlg.Destroy()
  79. class ErrorDialog(wx.Dialog):
  80. def __init__(self, parent, id, msg):
  81. super(ErrorDialog, self).__init__(parent, id, '提示信息', size=(600, 150))
  82. self.app = wx.GetApp()
  83. self.msg = msg
  84. self.sizer = wx.BoxSizer(wx.VERTICAL)
  85. self.sizer.Add(wx.StaticText(self, -1, self.msg), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, border=30)
  86. self.sizer.Add(wx.Button(self, wx.ID_OK), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM, border=0)
  87. self.SetSizer(self.sizer)
  88. class App(wx.App):
  89. def __init__(self):
  90. wx.App.__init__(self)
  91. def OnInit(self):
  92. self.dialog = MyFileDialog()
  93. self.dialog.Show(True)
  94. return True
  95. if __name__ == '__main__':
  96. app = App()
  97. app.MainLoop()

八. python日志配置

  1. import logging
  2. logger = logging.getLogger(__name__)
  3. logger.setLevel(level=logging.INFO)
  4. handler = logging.FileHandler("log.txt")
  5. handler.setLevel(logging.INFO)
  6. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  7. handler.setFormatter(formatter)
  8. logger.addHandler(handler)
  9. # 注意: 在logger.xxx()中添加一个exc_info=True参数,就可以将错误信息写入日志文件中了

openpyxl,xlrd,win32com,wxpython,logging的更多相关文章

  1. 【问题解决方案】ImportError: No module named 'openpyxl'/‘xlrd’

    背景: 在jupyter notebook to_excle: 运行将dataframe保存为excel文件 df.to_excel('dataframe.xlsx') 时报错openpyxl rea ...

  2. Python excel 库:Openpyxl xlrd 对比 介绍

    打算用python做一个写mtk camera driver的自动化工具. 模板选用标准库里面string -> Template 即可 但要重定义替换字符,稍后说明 配置文件纠结几天:cfg, ...

  3. Python操作excel的几种方式--xlrd、xlwt、openpyxl

    openpyxl xlrd xlwt   在处理excel数据时发现了xlwt的局限性–不能写入超过65535行.256列的数据(因为它只支持Excel 2003及之前的版本,在这些版本的Excel中 ...

  4. Python 读写操作Excel —— 安装第三方库(xlrd、xlwt、xlutils、openpyxl)

    数据处理是 Python 的一大应用场景,而 Excel 则是最流行的数据处理软件.因此用 Python 进行数据相关的工作时,难免要和 Excel 打交道. 如果仅仅是要以表单形式保存数据,可以借助 ...

  5. Python操作excel(xlrd和xlwt)

    Python操作excel表格有很多支持的库,例如:xlrd.xlwt.openpyxl.win32com,下面介绍使用xlrd.xlwt和xlutils模块这三个库不需要其他的支持,在任何操作系统上 ...

  6. Python处理Excel(转载)

    1. Python 操作 Excel 的函数库 我主要尝试了 3 种读写 Excel 的方法: 1> xlrd, xlwt, xlutils: 这三个库的好处是不需要其它支持,在任何操作系统上都 ...

  7. Python在Office 365 开发中的应用

    我在昨天发布的文章 -- 简明 Python 教程:人生苦短,快用Python -- 中提到了Python已经在Office 365开发中全面受支持,有不同朋友留言或私信说想了解更加详细的说明,所以特 ...

  8. Python 简单模块学习

    1. openpyxl / xlrd / xlwt  => 操作Excel 文件(xlsx格式) => xlrd + xlwt : 只能操作xls文件,分别负责读写, 暂时不讨论 => ...

  9. data cleaning

    Cleaning data in Python   Table of Contents Set up environments Data analysis packages in Python Cle ...

随机推荐

  1. 2440sd初始化(存储器控制器寄存器的设置)

    #define mem_contrl 0x48000000   //13个寄存器的基地址(看做一个内存块)init_sdram: ldr r0, =mem_contrl               / ...

  2. 13、SparkContext详解

    一.SparkContext原理 1.图解 二.SparkContext源码 1.TaskScheduler创建 ###SparkContext.scala // Create and start t ...

  3. 常用命令备忘 xargs

    xargs 作为使用率很高的命令,但是长久不用就会模糊了记忆,所以要记录下来. 获取所有的cobbler相关的布尔值然后全部设置为真 getsebool -a|grep cobbler|awk '{p ...

  4. C# 百度API地址坐标互相转换

    通过C#代码将地址字符串转为经纬度坐标,或者将经纬度转为具体的地址字符串,在不通外网的项目中是有需求的. 具体步骤: 一.创建BaiduMapHelper,用于定义地址信息和请求. public st ...

  5. 发布自己的类库包到Nuget

    今天来记录下发布自己的类库到Nuget. 一.准备工作 注册www.nuget.org,获取APIKey 后面发布要使用到. 二.创建项目 新建类库项目 新建测试demo类 public class ...

  6. 20190710用控制台启动一个wcf服务

    快速阅读 如何用控制台启动一个wcf服务,已经wcf的配置和在类库中如何实现 . wcf类库 用vs新建一个类库,引用system.ServiceModel 定义接口实现服务契约和操作契约 [Serv ...

  7. 像母语者一样说美语 How to Improve Spoken American English - Sound like a Native Speaker

    视频讲解: 视频详情见:https://www.bilibili.com/video/av75075387/ 总结分析: 001 要点总结: 1. 本富兰克林方法: 要你写下一切听到的东西 2. 辅音 ...

  8. virtualBox虚拟机Ubuntu系统与主机Windows共享文件夹

    1.在virtualBox虚拟机中安装Ubuntu系统 2.打开虚拟机后,安装VirtualBox增强功能包(VBoxGuestAdditions),参照下图,如果确认已经安装就直接跳过至第4步. 3 ...

  9. linux系统下以存储从大到小并以K,M,G为单位的方式查看当前目录下的文件信息

    zhuazai:https://blog.csdn.net/sty945/article/details/79830915 前言 ls命令 ls -a ls -l ll du命令 du -s du - ...

  10. CEF3设置cookie

    #include "CEF3Helper.h" #include "../include/cef_app.h" #include "../includ ...