2023-12-14 20:11:48 | 我爱编程网
在Excel中准备调用的python代码:
def merge_sort_unique(lists):
s = set()
for L in lists:
s.update(L)
return sorted(s)
任意在本地建立一个目录,并保存这个代码并命名为Methods.py。我们一步步看看如何从Excel的工作表中如何调用这个脚本。打开Excel,填写一些数据以便提供python脚本处理,并保持这个表格于刚才的python脚本在同一目录下。你的工作表应该如下:
接下来,打开VBA并提交给ExcelPython。
打开VBA按 Alt + F11 然后进入工具界面的 References···如果你已经正确安装了ExcelPython你可以从对话框中选择。
现在,备调用python脚本,创建一个新的模块(Insert | Module)并敲以下VBA代码:
Function msu(lists As Range)
Set methods = PyModule("Methods", AddPath:=ThisWorkbook.Path)
Set result = PyCall(methods, "merge_sort_unique", PyTuple(lists.Value2))
msu = WorksheetFunction.Transpose(PyVar(result))
ExitFunction
EndFunction
一、读excel表
读excel要用到xlrd模块,官网安装(
)。然后就可以跟着里面的例子稍微试一下就知道怎么用了。大概的流程是这样的:
1、导入模块
复制代码代码如下:
import xlrd
2、打开Excel文件读取数据
复制代码代码如下:
data = xlrd.open_workbook('excel.xls')
3、获取一个工作表
① table = data.sheets()[0] #通过索引顺序获取
② table = data.sheet_by_index(0) #通过索引顺序获取
③ table = data.sheet_by_name(u'Sheet1')#通过名称获取
4、获取整行和整列的值(返回数组)
复制代码代码如下:
table.row_values(i)
table.col_values(i)
5、获取行数和列数
复制代码代码如下:
table.nrows
table.ncols
6、获取单元格
复制代码代码如下:
table.cell(0,0).value
table.cell(2,3).value
就我自己使用的时候觉得还是获取cell最有用,这就相当于是给了你一个二维数组,余下你就可以想怎么干就怎么干了。得益于这个十分好用的库代码很是简洁。但是还是有若干坑的存在导致话了一定时间探索。现在列出来供后人参考吧:
1、首先就是我的统计是根据姓名统计各个表中的信息的,但是调试发现不同的表中各个名字貌似不能够匹配,开始怀疑过编码问题,不过后来发现是因为 空格。因为在excel中输入的时候很可能会顺手在一些名字后面加上几个空格或是tab键,这样看起来没什么差别,但是程序处理的时候这就是两个完全 不同的串了。我的解决方法是给每个获取的字符串都加上strip()处理一下。效果良好
2、还是字符串的匹配,在判断某个单元格中的字符串(中文)是否等于我所给出的的时候发现无法匹配,并且各种unicode也不太奏效,百度过一些解决 方案,但是都比较复杂或是没用。最后我采用了一个比较变通的方式:直接从excel中获取我想要的值再进行比较,效果是不错就是通用行不太好,个 呢不能问题还没解决。
二、写excel表
写excel表要用到xlwt模块,官网下载(
)。大致使用流程如下:
1、导入模块
复制代码代码如下:
import xlwt
2、创建workbook(其实就是excel,后来保存一下就行)
复制代码代码如下:
workbook = xlwt.Workbook(encoding = 'ascii')
3、创建表
复制代码代码如下:
worksheet = workbook.add_sheet('My Worksheet')
4、往单元格内写入内容
复制代码代码如下:
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
5、保存
复制代码代码如下:
workbook.save('Excel_Workbook.xls')
由于我的需求比较简单,所以这上面没遇到什么问题,唯一的就是建议还是用ascii编码,不然可能会有一些诡异的现象。
当然xlwt功能远远不止这些,他甚至可以设置各种样式之类的。附上一点例子
复制代码代码如下:
Examples Generating Excel Documents Using Python's xlwt
Here are some simple examples using Python's xlwt library to dynamically generate Excel documents.
Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:
The Simplest Example
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
workbook.save('Excel_Workbook.xls')
Formatting the Contents of a Cell
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
font = xlwt.Font() # Create the Font
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # Create the Style
style.font = font # Apply the Font to the Style
worksheet.write(0, 0, label = 'Unformatted value')
worksheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
workbook.save('Excel_Workbook.xls')
Attributes of the Font Object
font.bold = True # May be: True, False
font.italic = True # May be: True, False
font.struck_out = True # May be: True, False
font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC
font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT
font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE
font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I
font.colour_index = ?
font.get_biff_record = ?
font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height.
font.name = ?
font.outline = ?
font.shadow = ?
Setting the Width of a Cell
import xltw
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 'My Cell Contents')
worksheet.col(0).width = 3333 # 3333 = 1" (one inch).
workbook.save('Excel_Workbook.xls')
Entering a Date into a Cell
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save('Excel_Workbook.xls')
Adding a Formula to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])
workbook.save('Excel_Workbook.xls')
Adding a Hyperlink to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, xlwt.Formula('HYPERLINK("
";"Google")')) # Outputs the text "Google" linking to
workbook.save('Excel_Workbook.xls')
Merging Columns and Rows
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write_merge(0, 0, 0, 3, 'First Merge') # Merges row 0's columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style) # Merges row 1 through 2's columns 0 through 3.
workbook.save('Excel_Workbook.xls')
Setting the Alignment for the Contents of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
Adding Borders to a Cell
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
Setting the Background Color of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, 'Cell Contents', style)我爱编程网
workbook.save('Excel_Workbook.xls')
TODO: Things Left to Document
- Panes -- separate views which are always in view
- Border Colors (documented above, but not taking effect as it should)
- Border Widths (document above, but not working as expected)
- Protection
- Row Styles
- Zoom / Manification
- WS Props?
Source Code for reference available at:
我爱编程网(https://www.52biancheng.com)小编还为大家带来如何用Python将表格一整行条件格式化突出显示特定值?的相关内容。
实现思路其它比较简单
用python打开你的excel文件,
循环遍历每个单元各的内容。
检查这个单元格中的值是否符合你的条件。
如符合条件,单元格的背景色设为淡红色。
不符合条件,单无格的背景色设为淡绿色。
如有其它问题还可以追问。
如何使用PHP函数sprintf将字符串格式化如果有一个字符串$str='99.9';,怎么样使这个字符串变成99.90呢?我们需要用到PHP的格式化字符串函数sprintf()函数说明:sprintf(格式,要转化的字符串)返回:格式化好的字符串例子:$str='99.9';$result=sprintf('%01.2f',$str);echo$result;//结果显示99.90解释下,
PHP如何格式化数字?PHP格式化数字的函数是number_format我建议你去下载一个PHP的使用手册,或者看网上的在线手册也行。关于他的用法如下:语法:stringnumber_format(floatnumber,int[decimals],string[dec_point],string[thousands_sep]);返回值:字符串函数种类:数
plt.text怎么格式化输出一、使用print()函数在Python中,print()函数支持格式化输出,与C语言的printf类似。1.格式化输出字符串和整数2.格式化输出不同进制数3.格式化输出浮点数二、使用str.format()方法%操作符是传统格式化输出的基本方法,从Python2.6版本开始,为字符串数据新增了一种格式化方法str.format(),它通
求助thinkphp连接SQLserver2008拷贝php_sqlsrv_54_ts.dll到wampserver的bin\php\php5.4.3\ext文件夹下;添加extension=php_sqlsrv_54_ts.dll到php.iniconfig.php是这样设置的:'DB_TYPE'=>'sqlsrv',//数据库类型'DB_HOST'=>'192
求字符串处理函数(全)函数名:stpcpy功能:拷贝一个字符串到另一个用法:char*stpcpy(char*destin,char*source);程序例:#include<stdio.h>#include<string.h>intmain(void){charstring[10];char*str1="abcdefghi";
在php生成excel文档时怎样设定字体大小?PHP生成EXCEL有多种方法,不知道你的程序是用的哪种方法,各种方法的处理不一样。最简单的生产的<TAB>或者逗号分割的文本,这类文件无法设置格式。有的PHP实际上是生产的HTML,可以使用HTML代码控制格式,比如<FONTCOLOR=XXXSIZE=X>。有的PHP实际上是生产的XML,这类可以在C
PHP输出图像imagegif、imagejpeg与imagepng函数用法分析本文实例讲述了PHP输出图像imagegif、imagejpeg与imagepng函数用法。分享给大家供大家参考,具体如下:imagegif()、imagejpeg()、imagepng()和imagewbmp()函数分别允许以GIF、JPEG、PNG和WBMP格式将图像输出到浏览器或文件。PHP输出图像
按引用传递参数用php来表示圆柱的表面积?下面是一个使用按引用传递参数的PHP函数,用于计算圆柱的表面积:functioncylinder_surface_area($radius,$height,&$surface_area){$surface_area=2*pi()*$radius*$height+2*pi()*pow($radius,2);}//示例用法$
2025-02-01 20:24:39
2024-01-05 14:11:24
2025-02-10 15:19:48
2025-01-28 17:58:32
2024-11-22 05:08:01
2024-09-10 08:50:00