这里写自定义目录标题
- 单元格嵌入图片
- 调节行高和列宽
- 合并单元格
- 自动换行
- 按列插入数据
- tableWidget数据导出到excel
单元格嵌入图片
from openpyxl.drawing.image import Image
from openpyxl.drawing.spreadsheet_drawing import AnchorMarker, TwoCellAnchor
from openpyxl.workbook import Workbook
wb = Workbook()
sheet = wb.create_sheet('Sheet1')
def cell_insert_image(sub_sheet, img_path, row_index, col_index):
# 读取图像
img = Image(img_path)
# 左上角固定一个单元格,索引从0开始,AnchorMarker(列,微调,行,微调)
_from = AnchorMarker(row_index, 50000, col_index, 50000)
# 右下角固定到另一个单元格
to = AnchorMarker(row_index + 1, -50000, col_index + 1, -50000)
img.anchor = TwoCellAnchor('twoCell', _from, to)
sub_sheet.add_image(img)
# 设置的行高和列宽
sub_sheet.row_dimensions[2].height = 100
sub_sheet.column_dimensions['B'].width = 100
cell_insert_image(sheet, r"d69160564a32f8e1ba6b36ae5831f069.jpg", 1, 1)
wb.save("单元格嵌入图片.xlsx")
调节行高和列宽
sub_sheet.row_dimensions[2].height = 100 #索引从1开始
sub_sheet.column_dimensions['B'].width = 100
合并单元格
import openpyxl
wb = openpyxl.load_workbook('单元格嵌入图片.xlsx')
sheet = wb['Sheet']
# 合并第一行的第1-3列的单元格
sheet.merge_cells(start_row=1, end_row=1, start_column=1, end_column=3)
# 合并第一列的第3-4行
sheet.merge_cells(start_row=3, end_row=4, start_column=1, end_column=1)
wb.save('单元格嵌入图片.xlsx')
自动换行
import openpyxl
from openpyxl.styles import Alignment
wb = openpyxl.load_workbook('单元格嵌入图片.xlsx')
sheet = wb['Sheet2']
for cell in sheet['B']:
cell.alignment = Alignment(wrapText=True)
wb.save('单元格嵌入图片.xlsx')
按列插入数据
import openpyxl
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from openpyxl.utils import column_index_from_string
def insert_list_data_to_column(sub_sheet, list_data, column_name, start_row=1):
col_index = column_index_from_string(column_name)
for row_index in range(start_row, start_row + len(list_data)):
col_val = list_data[row_index - start_row]
try:
sub_sheet.cell(row=row_index, column=col_index, value=col_val)
except Exception as e:
col_val = ILLEGAL_CHARACTERS_RE.sub(r'', col_val)
sub_sheet.cell(row=row_index, column=col_index, value=col_val)
insert_data = {'A': ['测试数据', 1, 2, 3, 4, 5,6],
'B': ['测试结果', 'passed', 'failed', 'passed', 'passed', 'passed', 'passed']}
wb = openpyxl.load_workbook('单元格嵌入图片.xlsx')
sheet = wb.create_sheet("Sheet3")
for column_name, list_value in insert_data.items():
insert_list_data_to_column(sheet, list_value, column_name=column_name, start_row=1)
wb.save('单元格嵌入图片.xlsx')
tableWidget数据导出到excel
注意:openpyxl的行列索引都是从1开始,单元格的数据类型是str
import openpyxl
from PyQt5.QtWidgets import QTableWidget
wb = openpyxl.Workbook()
ws = wb.active
# tableWidget不再赘述其定义方式
# 插入表头
tableWidget: QTableWidget
for index in range(tableWidget.colorCount()):
ws.cell(row=1, column=index + 1, value=tableWidget.horizontalHeaderItem(index).text())
# 插入数据
for row in range(tableWidget.rowCount()):
for col in range(tableWidget.colorCount()):
item = tableWidget.item(row, col)
if item is not None:
ws.cell(row=row + 2, column=col + 1, value=str(item.text()))
wb.save("导出.xlsx")