两个案例+xlwings
作者:互联网
案例一 把文件夹名字整理到Excel里
import os
import xlwt
file_path = 'd:/'
# 取出目标文件夹下的文件名
os.listdir(file_path)
# 新建工作簿,sheet
new_workbook = xlwt.Workbook()
sheet = new_workbook.add_sheet('new_dir')
# 取出文件名,依次写入
n = 0
for i in os.listdir(file_path):
sheet.write(n,0,i)
n += 1
new_workbook.save('dir.xls')
案例二 用Excel作画,将一张图以图块的形式输出到Excel
from PIL import Image
from xlsxwriter.workbook import Workbook
class ExcelPicture(object):
FORMAT_CONSTRAINT = 65536
def __init__(self, pic_file, ratio=0.5):
self.__pic_file = pic_file
self.__ratio = ratio
self.__zoomed_out = False
self.__formats = dict()
# 缩小图片
def zoom_out(self, _img):
_size = _img.size
_img.thumbnail((int(_img.size[0] * self.__ratio), int(_img.size[1] * self.__ratio)))
self.__zoomed_out = True
# 对颜色进行圆整
def round_rgb(self, rgb, model):
return tuple([int(round(x / model) * model) for x in rgb])
# 查找颜色样式,去重
def get_format(self, color):
_format = self.__formats.get(color, None)
if _format is None:
_format = self.__wb.add_format({'bg_color': color})
self.__formats[color] = _format
return _format
# 操作流程
def process(self, output_file='_pic.xlsx', color_rounding=False, color_rounding_model=5.0):
# 创建xlsx文件,并调整行列属性
self.__wb = Workbook(output_file)
self.__sht = self.__wb.add_worksheet()
self.__sht.set_default_row(height=9)
self.__sht.set_column(0, 5000, width=1)
# 打开需要进行转换的图片
_img = Image.open(self.__pic_file)
print('Picture filename:', self.__pic_file)
# 判断是否需要缩小图片尺寸
if self.__ratio < 1:
self.zoom_out(_img)
# 遍历每一个像素点,并填充对应的颜色到对应的Excel单元格
_size = _img.size
print('Picture size:', _size)
for (x, y) in [(x, y) for x in range(_size[0]) for y in range(_size[1])]:
_clr = _img.getpixel((x, y))
# 如果颜色种类过多,则需要将颜色圆整到近似的颜色上,以减少颜色种类
if color_rounding: _clr = self.round_rgb(_clr, color_rounding_model)
_color = '#%02X%02X%02X' % _clr
self.__sht.write(y, x, '', self.get_format(_color))
self.__wb.close()
# 检查颜色样式种类是否超出限制,Excel2007对样式数量有最大限制
format_size = len(self.__formats.keys())
if format_size >= ExcelPicture.FORMAT_CONSTRAINT:
print('Failed! Color size overflow: %s.' % format_size)
else:
print('Success!')
print('Color: %s' % format_size)
print('Color_rounding:', color_rounding)
if color_rounding:
print('Color_rounding_model:', color_rounding_model)
if __name__ == '__main__':
r = ExcelPicture('wallhaven-l317xp.jpg', ratio=0.5) # 图片放在同级目录
r.process('wallhaven-l317xp.xlsx', color_rounding=True, color_rounding_model=5.0)
#
#
# # pandas_数据透视表
#
import pandas as pd
import numpy as np
r_file = pd.ExcelFile('student.xls')
data = r_file.parse('Sheet1')
print(data)
# index代表行,columns代表列
# aggfunc = np.sum 求和
# margins=True 总计
pt_s = pd.pivot_table(data, index=['省份'], aggfunc = np.sum, margins=True) # aggfunc = np.sum 求和,默认为平均值
# 全部显示行和列
pt_s.set_option('display.max_rows', None)
pt_s.set_option('display.max_columns', None)
# 求各省的个数
pt_n = pd.pivot_table(data, index=['省份'], aggfunc=np.size, margins=True) # aggfunc=np.sum 求和,默认是平均值
print(pt_s.iat[0, 0])
print(pt_n.iat[0, 0])
import os
path = 'example.xlsx'
separate = os.path.splitext(path)
print(separate)
'''
# 利用xlwings创建空工作簿并关闭
import xlwings as xw
app = xw.App(visible=True,add_book=False)
workbook = app.books.add()
workbook.save('d:\\example.xlsx')
workbook.close() # 关闭工作簿
app.quit() # 退出Excel程序
# 打开已有工作簿
import xlwings as xw
app = xw.App(visible=True,add_book=False)
workbook = app.books.open(r'd:\example.xlsx') # 打开D盘根文件夹下工作簿
'''
'''
# 案例1
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.add()
worksheet = workbook.sheets.add('产品统计表')
worksheet.range('A1').value = '编号'
workbook.save(r'd:\beijing.xlsx')
workbook.close()
app.quit()
# 案例2
# 操控工作表和单元格
worksheet = workbook.sheets['Sheets'] # 选中工作表
worksheet.range('A1').value = '编号' # 在单元格A1中输入编号
worksheet = workbook.sheets.add('产品统计') #新增一个工作表,名称为“产品统计“
import xlwings as xw
app = xw.App(visible = False)
workbook = app.books.add()
worksheet = workbook.sheets.add('产品统计表')
worksheet.range('A1').value = '编号'
workbook.save(r'd:\统计x.xlsx')
workbook.close
app.quit
'''
标签:.__,两个,format,color,self,xlwings,案例,workbook,size 来源: https://www.cnblogs.com/chengfo/p/16528024.html