Luckysheet 导出图片部分demo #python
公司需要做个自己的在线文档处理系统,找了半天开源项目,用的觅思文档,python语言,导出部分需要收费,只能二开,核心使用luckysheet,导出图片部分代码demo如下:
参考博客:https://blog.csdn.net/qq_49496611/article/details/135057163
代码如下:
// An highlighted block
import os
import base64
from io import BytesIO
from openpyxl.drawing.image import Image
import openpyxl
import json
from openpyxl import Workbook
def setImages(sheet, images, visibledatacolumn, visibledatarow):
print("++====+开始处理图片+++++")
for key in images:
image_binary = base64.b64decode(images[key]["src"].split(",")[1])
myBase64Image = Image(BytesIO(image_binary))
item = images[key]
col_st = int(getImagePosition(item["default"]["left"], visibledatacolumn))
row_st = int(getImagePosition(item["default"]["top"], visibledatarow))
myBase64Image.width, myBase64Image.height = item["default"]["width"], item["default"]["height"]
cell_coordinate = openpyxl.utils.get_column_letter(col_st + 1) + str(row_st + 1)
myBase64Image.anchor = cell_coordinate # 设置锚点为单元格坐标字符串
sheet.add_image(myBase64Image)
def getImagePosition(num, arr):
print("++====+开始处理图片位置+++++")
index = 0
for i in range(0, len(arr)):
if num < arr[i]:
index = i
break
if index == 0:
minIndex = 0
maxIndex = 1
return abs((num - 0) / (arr[maxIndex] - arr[minIndex])) + index
elif index == len(arr) - 1:
minIndex = len(arr) - 2
maxIndex = len(arr) - 1
else:
minIndex = index - 1
maxIndex = index
min = arr[minIndex]
max = arr[maxIndex]
return abs((num - min) / (max - min)) + index
# 使用示例:
current_path = os.path.dirname(os.path.abspath(__file__))
jsonFilePath = current_path + '\\test_data.json' # luckysheet工作表数据源json
try:
with open(jsonFilePath, 'r', encoding='utf-8') as f:
json_data = json.load(f)
except json.decoder.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
json_data = json_data[0] # 仅处理第一个sheet
workbook = Workbook()
sheet = workbook.active
sheet.title = json_data["name"]
# 简单内容导出
for row_index, row in enumerate(json_data["data"]):
for col_index, cell in enumerate(row):
if cell and "v" in cell:
value = cell["v"]
sheet.cell(row=row_index + 1, column=col_index + 1).value = value
# 图片导出处理
setImages(sheet, json_data["images"], json_data["visibledatacolumn"], json_data["visibledatarow"])
# 保存工作簿
print(workbook)
workbook.save("output.xlsx")