openpyxl的基础运用

from rest_framework.views import APIView
from openpyxl import Workbook
# 单元格颜色填充
from openpyxl.styles import Border, Side, Font, Alignment, PatternFill
from openpyxl.utils import get_column_interval, get_column_letter, column_index_from_string

# 图片
from openpyxl.drawing.image import Image
import time


class DerivedBomData(APIView):
"""获取bom数据"""

def get(self, request):
try:
wb = Workbook() # 实例化
ws = wb.active # 激活 worksheet
ws.title = '报价单'
# 合并单元格
ws.merge_cells('A1:M1')
ws.merge_cells('A2:K2')
ws.merge_cells('A3:D3')
ws.merge_cells('E3:K3')
# A1 格式
ws["A1"] = "BOM报价单"
# name表示字体 ,italic是否斜体,color颜色,bold加粗
font = Font(name='微软雅黑', size=24, bold=True)
# horizontal代表水平方向,可以左对齐left,还有居中center和右对齐right,分散对齐distributed,跨列居中centerContinuous,两端对齐justify,填充fill,常规general
# vertical代表垂直方向,可以居中center,还可以靠上top,靠下bottom,两端对齐justify,分散对齐distributed
# 另外还有自动换行:wrap_text,这是个布尔类型的参数,这个参数还可以写作wrapText
align = Alignment(horizontal='center', vertical='center')
ws["A1"].font = font
ws["A1"].alignment = align
img = Image(settings.IMAGE_PSTH)
newsize = (300, 100)
img.width, img.height = newsize # 这两个属性分别是对应添加图片的宽高

ws.add_image(img, 'A1') # 向D3单元格内指定添加图片
border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))

# 调整行高和列宽s
ws.column_dimensions['A'].width = 30.0 # 调整列宽
ws.column_dimensions['B'].width = 30.0 # 调整列宽
ws.column_dimensions['C'].width = 20.0 # 调整列宽
ws.column_dimensions['D'].width = 20.0
ws.column_dimensions['E'].width = 30.0
ws.column_dimensions['F'].width = 30.0
ws.column_dimensions['G'].width = 30.0
ws.column_dimensions['H'].width = 20.0
ws.column_dimensions['I'].width = 20.0
ws.column_dimensions['J'].width = 20.0
ws.column_dimensions['K'].width = 20.0
ws.column_dimensions['L'].width = 30.0
ws.column_dimensions['M'].width = 30.0

# 调整行高
ws.row_dimensions[1].height = 80 # 第一行行高
for i in range(2, 1000):
ws.row_dimensions[i].height = 30 # 调整行高

# 单元格颜色填充, 设置样式,并且加载到对应单元格
fill = PatternFill("solid", fgColor="FFDAB9")
for i in get_column_interval('E', 'M'):
a = i + str(4)
ws[a].fill = fill

# A2格式
ws["A2"] = "您好,如有需要请与我们联络:xxxxxx"
# name表示字体 ,italic是否斜体,color颜色,bold加粗
font = Font(name='微软雅黑', size=10, bold=False)
align = Alignment(horizontal='left', vertical='center')
ws["A2"].font = font
ws["A2"].alignment = align

# H2
ws["M2"] = "本报价有效期为3天"
# name表示字体 ,italic是否斜体,color颜色,bold加粗
font = Font(name='微软雅黑', size=10, bold=False)
align = Alignment(horizontal='left', vertical='center')
ws["M2"].font = font
ws["M2"].alignment = align

# A3格式
ws["A3"] = bom_name
# name表示字体 ,italic是否斜体,color颜色,bold加粗
font = Font(name='微软雅黑', size=14, bold=True)
align = Alignment(horizontal='center', vertical='center')
ws["A3"].font = font
ws["A3"].alignment = align

# A3格式
ws["E3"] = "报价"
font = Font(name='微软雅黑', size=14, bold=True)
align = Alignment(horizontal='center', vertical='center')
ws["E3"].font = font
ws["E3"].alignment = align

# 插入表头
tableTitle = ['需求型号', '规格参数', '采购数量', '厂牌', '型号', '供应商', '供应商联系方式', '厂牌', '货期', '数量', '单价', '小计']
for col in range(len(tableTitle)):
c = col + 1
ws.cell(row=4, column=c).value = tableTitle[col]

# 插入价格小计
max_row = ws.max_row # 获取当前最大行
row_4_start = 'L' + str(max_row + 2)
price_count = '¥' + str(total_prices)
ws[row_4_start] = price_count
font = Font(name='微软雅黑', size=14, bold=True)
ws[row_4_start].font = font

# 为整个表格加上边框
max_row = ws.max_row
for i in get_column_interval('A', 'M'):
for row in range(4, max_row - 1):
a = i + str(row)
ws[a].border = border
font = Font(name='微软雅黑', size=10, bold=False)
ws[a].font = font
# H3格式
ws["M3"] = "总价(含税): " + str(total_prices)
# name表示字体 ,italic是否斜体,color颜色,bold加粗
font = Font(name='微软雅黑', size=10, bold=False)
align = Alignment(horizontal='left', vertical='center')
ws["M3"].font = font
ws["M3"].alignment = align
# 导出的excel文件名
time_1 = time.strftime('%Y_%m_%d')
filename = bom_name + '_' + str(time_1) + '.xlsx'
# 准备写入到IO中
output = BytesIO()
wb.save(output) # 将Excel文件内容保存到IO中
output.seek(0) # 重新定位到开始
# 设置HttpResponse的类型
response = HttpResponse(output.getvalue(), content_type='application/vnd.ms-excel')
file_name = urlquote(filename) # 使用urlquote()方法解决中文无法使用的问题
response['Content-Disposition'] = 'attachment; filename=%s' % file_name
return response
except Exception as e:
print(e)
meta = get_http_meta(self, request)
# 请求时间 - 响应时间 - 模块名 - 文件名 - 方法名 - 日志级别: HTTP_HOST - REMOTE_ADDR - UUID - PATH_INFO - QUERY_STRING - "错误描述"
log.error(
"{} - infinigo_app_home.bom - view.py - GetElectronDetail - error : {} - {} - {} - {} - {} - {}".format(
meta['time_now'],
meta[
'HTTP_HOST'],
meta[
'REMOTE_ADDR'],
meta['UUID'],
meta[
'PATH_INFO'],
meta[
'QUERY_STRING'],
e))
return Response({"code": 400, "zh_message": "bom导出功能报错", "en_message": ""})
上一篇:2D池化IPoolingLayer


下一篇:Accelerate Your CNN from Three Dimensions: A Comprehensive Pruning Framework