怎么将word中的times new roman的双引号替换成宋体双引号

本文档详细介绍了在Word处理过程中遇到的一个问题:在尝试将汉字设置为宋体,数字和英文字母改为TimesNewRoman时,中文引号意外也被转换成了TimesNewRoman。通过使用通配符和格式替换功能进行操作,虽然成功改变了字母和数字的字体,但中文引号的字体也随之改变。解决方案和具体步骤在文中进行了详细说明。

近期因为处理文档过程中要把汉字使用宋体而数字和英文字母使用Times New Roman。我们先把正文成段或者成片地改成了宋体,然后成段地再将正文改成Times New Roman,替换完成后,英文字母和数字确实变成了Times New Roman,但是中文的引号也变成Times New Roman。也就是下图所示:

 下图中表格第二列的双引号是修改后的:

 具体来说,替换过程如下:
(1)使用通配符进行查找,在搜索选项中勾选通配符

(2)查找内容框中输入:[“”],注意不是[""],我们要输入的是中文的双引号,而不是英文的双引号;

(3)选择左下角格式--字体--西文--Times New Roman;

(4)替换为框中不写内容,但是选择格式--字体--西文--宋体;

(5)选择全部替换。

 

from openpyxl import load_workbook from docx import Document from docx.shared import Inches from docx.shared import Pt, Cm from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING # 添加WD_LINE_SPACING from docx.enum.style import WD_STYLE_TYPE from docx.enum.table import WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE from docx.oxml.ns import qn from docx.oxml import OxmlElement from docxcompose.composer import Composer import re def insert_entire_document(main_doc_path, insert_doc_path, output_path): """ 将整个插入文档内容添加到主文档末尾 参数: main_doc_path: 主文档路径 insert_doc_path: 要插入的文档路径 output_path: 输出文档路径 """ # 读取主文档 main_doc = Document(main_doc_path) # 读取要插入的文档 insert_doc = Document(insert_doc_path) # 创建Composer对象进行文档合并 composer = Composer(main_doc) # 将插入文档追加到主文档 composer.append(insert_doc) # 保存合并后的文档 composer.save(output_path) print(f"文档已成功合并保存至: {output_path}") def set_cell_margins(cell, left=0.05, right=0.05, top=None, bottom=None): """ 设置Word表格单元格边距(单位:厘米) 参数: cell: 要设置的单元格对象 left: 左边距(厘米),默认为0.05 right: 右边距(厘米),默认为0.05 top: 上边距(厘米),可选 bottom: 下边距(厘米),可选 """ # 确保单位为厘米 left = float(left) if left is not None else None right = float(right) if right is not None else None top = float(top) if top is not None else None bottom = float(bottom) if bottom is not None else None # 获取单元格属性 tc = cell._tc tcPr = tc.get_or_add_tcPr() # 创建或获取单元格边距元素 tcMar = tcPr.first_child_found_in('w:tcMar') if tcMar is None: tcMar = OxmlElement('w:tcMar') tcPr.append(tcMar) # 创建边距元素并设置值 directions = { 'left': left, 'right': right, 'top': top, 'bottom': bottom } for direction, value in directions.items(): if value is None: continue # 转换厘米为缇(twips): 1厘米 = 567缇 twips = str(int(value * 567)) # 查找或创建方向元素 dir_element = tcMar.find(qn(f'w:{direction}')) if dir_element is None: dir_element = OxmlElement(f'w:{direction}') dir_element.set(qn('w:w'), twips) dir_element.set(qn('w:type'), 'dxa') # dxa表示单位为缇 tcMar.append(dir_element) else: dir_element.set(qn('w:w'), twips) def set_table_cell_margins(table, left=0.05, right=0.05, top=None, bottom=None): """ 设置整个表格所有单元格的边距 参数: table: 表格对象 left: 左边距(厘米),默认为0.05 right: 右边距(厘米),默认为0.05 top: 上边距(厘米),可选 bottom: 下边距(厘米),可选 """ for row in table.rows: for cell in row.cells: set_cell_margins(cell, left, right, top, bottom) def add_formatted_text(paragraph, text): """ 添加带格式的文本到段落中,自动处理斜体、上标和下标 格式规则: - U 和 k 设置为斜体 - rel 设置为下标 - 科学计数法中的负指数设置为上标 """ # 定义格式标记的正则表达式 patterns = [ (r'U(rel)?', 'u'), # 匹配U或Urel (r'k=', 'k'), # 匹配k= (r'×10(-\d+)', 'superscript'), # 匹配×10-数字 (r'rel', 'subscript'), # 单独匹配rel (r'%', 'normal'), # 百分号 (r'dB', 'normal'), # dB单位 ] # 位置标记数组 (0=普通, 1=斜体, 2=上标, 3=下标) flags = [0] * len(text) # 应用格式标记 for pattern, flag_type in patterns: for match in re.finditer(pattern, text): start, end = match.span() flag_value = { 'u': 1, 'k': 1, 'superscript': 2, 'subscript': 3, 'normal': 0 }[flag_type] # 特殊处理Urel组合 if flag_type == 'u' and match.group(1): flags[start] = 1 # U斜体 for i in range(start + 1, end): flags[i] = 3 # rel下标 else: for i in range(start, end): flags[i] = flag_value # 分割并添加格式化的文本片段 start_idx = 0 for i in range(1, len(flags)): if flags[i] != flags[i - 1]: segment = text[start_idx:i] add_segment(paragraph, segment, flags[i - 1]) start_idx = i # 添加最后一段 add_segment(paragraph, text[start_idx:], flags[-1]) def add_segment(paragraph, text, flag): """添加指定格式的文本片段""" if not text: return run = paragraph.add_run(text) run.font.size=Pt(12) run.font.name = 'Times New Roman' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 应用格式 if flag == 1: # 斜体 (U/k) run.italic = True elif flag == 2: # 上标 (科学计数法指数) run.font.superscript = True elif flag == 3: # 下标 (rel) run.font.subscript = True def excel_sheets_to_word(excel_path, word_path, lieshu): # 加载Excel工作簿 wb = load_workbook(excel_path, data_only=True) # 创建/加载Word文档 try: doc = Document(word_path) except: doc = Document() # 文件不存在时创建文档 # 遍历所有sheet sheetn = 0 xuhaon = 0 xuhao = ["二、", "三、", "四、", "五、", "六、", "七、"] biaotizhu=["","","(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)",'(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)','(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)',''] # 创建标题样式对象(设置全局行距) title_style = doc.styles.add_style('TitleStyle', WD_STYLE_TYPE.PARAGRAPH) title_style.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE title_style.paragraph_format.line_spacing = 1.5 # 设置为1.5倍行距 panju = 0 for sheet_name in wb.sheetnames: sheet = wb[sheet_name] max_row = sheet.max_row max_col = sheet.max_column # 检测有效数据范围(跳过开头和结尾的空行) start_row = 1 end_row = max_row # 查找第一个非空行(从顶部) for row_idx in range(1, max_row + 1): if any(sheet.cell(row=row_idx, column=col).value for col in range(1, max_col + 1)): start_row = row_idx break # 查找最后一个非空行(从底部) for row_idx in range(max_row, 0, -1): if any(sheet.cell(row=row_idx, column=col).value for col in range(1, max_col + 1)): end_row = row_idx break zd = lieshu[sheetn] if sheet_name == "相对电平": xuhaon = xuhaon - 1 else: # 创建标题段落并指定样式 title = doc.add_paragraph(style='TitleStyle') title_xu = xuhao[xuhaon] + sheet_name title_run = title.add_run(title_xu) title_run.bold = True # 设置加粗 title_run.font.size = Pt(14) title_zhu=title.add_run(biaotizhu[xuhaon]) title_zhu.font.size=Pt(10.5) title_zhu.bold=False title.alignment = WD_ALIGN_PARAGRAPH.LEFT # 确保行距设置应用到段落(双重保证) title.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE title.paragraph_format.line_spacing = 1.5 table = doc.add_table(rows=1, cols=zd) # 固定4列 table.style = 'Table Grid' # 添加表头(第一行数据作为标题) header_cells = table.rows[0].cells for col in range(1, zd + 1): # 只取前4列 header_cells[col - 1].text = str(sheet.cell(row=1, column=col).value or "") # 添加数据行(从第二行开始) for row in range(2, end_row + 1): row_cells = table.add_row().cells for col in range(1, zd + 1): # 只取前4列 cell_value = sheet.cell(row=row, column=col).value data_cell = str(cell_value) if cell_value is not None else "" # print(data_cell) if "*" in "9.9999934*": panju="不合格" # print(panju) else: pass data_cell = data_cell.replace("–", "-") data_cell = data_cell.replace("HZ", "Hz") row_cells[col - 1].text = data_cell set_table_cell_margins(table, 0.05, 0.05) # if zd >= 4: # 确保表格至少有4列 # table.columns[3].width = Cm(7) # 索引3对应第4列 # table.autofit = True # print(f"已设置表格 '{sheet_name}' 第4列宽度为7cm(列数={zd})") # else: # print(f"警告:表格 '{sheet_name}' 仅 {zd} 列,无法设置第4列宽度") # 设置单元格居中 for row in table.rows: if zd >= 4: row.cells[3].width = Cm(7) row.height_rule = WD_ROW_HEIGHT_RULE.AUTO # 自动调整行高 for cell in row.cells: cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER for paragraph in cell.paragraphs: paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 设置表格字体 for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') run.font.size = Pt(12) sheetn = sheetn + 1 xuhaon = xuhaon + 1 measurements = [ "频率扩展不确定度Urel =3.6×10-10~5.8×10-9(k=2),(10MHz~40GHz)", "功率扩展不确定度U=0.19dB~0.75dB(k=2),(10MHz~40GHz,-90dBm~+20dBm)", "调幅深度扩展不确定度Urel =1.2%(k=2),(10MHz~40GHz,5%~90%)", "调频频偏扩展不确定度Urel=1.2%(k=2),(10MHz~40GHz,4kHz~400kHz)", "调相相偏扩展不确定度Urel=1.2%(k=2),(10MHz~40GHz,4rad~400rad)", "频谱纯度扩展不确定度U=0.5dB~2.3dB(k=2),(10MHz~40GHz)" ] if panju=="不合格": measurements.append("注:本次校准结果中标”*”号项目不符合技术指标要求。") else: measurements.append("注:本次校准结果符合技术指标要求。") # 添加带格式的测量数据 for item in measurements: p = doc.add_paragraph(style='TitleStyle') add_formatted_text(p, item) t1=doc.add_paragraph(style='TitleStyle') run_t1 = t1.add_run("以下无内容") run_t1.font.size = Pt(12) run_t1.font.name = 'Times New Roman' # run_t1.font.name = u'黑体' # 中文字体 run_t1._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') run_t1.font.bold = True # text_parts = [ # ("频率扩展不确定度", None), # ("U", 'italic'), # ("rel", "subscript"), # rel下标 # ("=3.6×10", None), # ("-10", "superscript"), # -10上标 # ("~5.8×10", None), # ("-9", "superscript"), # -9上标 # (" (", None), # ("k", "italic"), # k斜体 # ("=2)", None), # (",(10MHz~40GHz)", None) # ] # # # 逐个添加带格式的文本片段 # t1=doc.add_paragraph(style='TitleStyle') # for text, format_type in text_parts: # run = t1.add_run(text) # run.font.size=Pt(12) # run.font.name = 'Times New Roman' # # run.font.name = u'宋体' # 中文字体 # run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 设置中文字体 # # if format_type == "superscript": # run.font.superscript = True # elif format_type == "subscript": # run.font.subscript = True # elif format_type == "italic": # run.italic = True # 保存Word文档 doc.save("newword.docx") # 使用示例 excel_path = "信号源数据模板.xlsx" # Excel文件路径 word_path = "信号源原始记录.docx" # 输出Word路径 lieshulist = [2, 4, 4, 4, 4, 4, 4] excel_sheets_to_word(excel_path, word_path, lieshulist) 我的代码如上,如何修改代码,使得注:本次校准结果中标”*”号项目不符合技术指标要求。这段文字中引号在word文档中为中文字体
09-03
import requests import re import os from docx import Document from docx.shared import Pt from docx.oxml.ns import qn from bs4 import BeautifulSoup if __name__=='__main__': url=input('请输入对应网址:') headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0' } Cookie={ 'cookie':'csrftoken=fbe5654d5ce83ec2f77fb8265ca6ef27; _c_WBKFRo=BxHewbXj0jgurJBaenjkJm7f51GW8wZdU0Z53DfF; sessionid="e30:1v7mAK:Ia-1DMV7xRUrhNauLTu7y23NUws"; auth_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjQ3NjU0NzY2LCJleHAiOjE3NjgwOTI1NDMsImV4cF92MiI6MTc2ODA5MjU0MywiZGV2aWNlIjoiIiwidXNlcm5hbWUiOiJXZWNoYXRfYjJiMmUxZWUyZTY4NzhmNiIsImlzX3N0YWZmIjowLCJzZXNzaW9uX2lkIjoiNmExM2E1YTZhN2NlMTFmMGEwNTFkYTk1YmMxZGI4YmYifQ.d9KETrwA3btkEtFCs7dfGWOlMTkhUXCruvEtstTPvhQ; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22eljiro%22%2C%22first_id%22%3A%22199c67799b245b-0b1c32464a818b8-4c657b58-2359296-199c67799b3e85%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%22199c67799b245b-0b1c32464a818b8-4c657b58-2359296-199c67799b3e85%22%7D' } response= requests.get(url,headers=headers,cookies= Cookie) response.encoding = response.apparent_encoding response=response.json() name=response.get('title_cn') print(name) name=input("请输入文章名称:") r=response.get('content') soup = BeautifulSoup(r, 'html.parser') if not os.path.exists("D:\爬虫/扇贝"): os.mkdir("D:\爬虫/扇贝") path="D:\爬虫\扇贝./"+name+".txt" with open(path, 'w', encoding='utf-8') as f: for para in soup.find_all('para'): f.write(para.text+'\n') f.close() def TXT_TO_WORD(path): # 创建一个空白的Word文档对象 doc = Document() # 指定要读取的txt文件路径 txt_file_path = path # 替换为你的实际txt文件路径 # 打开txt文件并逐行读取内容 with open(txt_file_path, 'r', encoding='utf-8') as file: for line in file: # 去除每行末尾的换行符,并添加到Word文档中作为一段 doc.add_paragraph(line.strip()) style = doc.styles['Normal'] style.font.name = 'Times New Roman' # 设置西文字体 style._element.rPr.rFonts.set(qn('w:ascii'), 'Times New Roman') style._element.rPr.rFonts.set(qn('w:hAnsi'), 'Times New Roman') style._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') # 中文字体(可改为仿宋、楷体等) style.font.size = Pt(10.5) # 五号字 = 10.5 磅 # 保存为Word文档 doc.save("D:\爬虫\扇贝./"+name+'.docx') TXT_TO_WORD(path) print("TXT文件已成功转换为Word格式!") os.remove(path) # https://apiv3.shanbay.com/news/articles/qtxle?source=1
最新发布
12-03
from openpyxl import load_workbook from docx import Document from docx.shared import Inches from docx.shared import Pt, Cm from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING # 添加WD_LINE_SPACING from docx.enum.style import WD_STYLE_TYPE from docx.enum.table import WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE from docx.oxml.ns import qn from docx.oxml import OxmlElement from docxcompose.composer import Composer import re import pandas as pd def insert_entire_document(main_doc_path, insert_doc_path, output_path): """ 将整个插入文档内容添加到主文档末尾 参数: main_doc_path: 主文档路径 insert_doc_path: 要插入的文档路径 output_path: 输出文档路径 """ # 读取主文档 main_doc = Document(main_doc_path) # 读取要插入的文档 insert_doc = Document(insert_doc_path) # 创建Composer对象进行文档合并 composer = Composer(main_doc) # 将插入文档追加到主文档 composer.append(insert_doc) # 保存合并后的文档 composer.save(output_path) print(f"文档已成功合并保存至: {output_path}") def set_cell_margins(cell, left=0.05, right=0.05, top=None, bottom=None): """ 设置Word表格单元格边距(单位:厘米) 参数: cell: 要设置的单元格对象 left: 左边距(厘米),默认为0.05 right: 右边距(厘米),默认为0.05 top: 上边距(厘米),可选 bottom: 下边距(厘米),可选 """ # 确保单位为厘米 left = float(left) if left is not None else None right = float(right) if right is not None else None top = float(top) if top is not None else None bottom = float(bottom) if bottom is not None else None # 获取单元格属性 tc = cell._tc tcPr = tc.get_or_add_tcPr() # 创建或获取单元格边距元素 tcMar = tcPr.first_child_found_in('w:tcMar') if tcMar is None: tcMar = OxmlElement('w:tcMar') tcPr.append(tcMar) # 创建边距元素并设置值 directions = { 'left': left, 'right': right, 'top': top, 'bottom': bottom } for direction, value in directions.items(): if value is None: continue # 转换厘米为缇(twips): 1厘米 = 567缇 twips = str(int(value * 567)) # 查找或创建方向元素 dir_element = tcMar.find(qn(f'w:{direction}')) if dir_element is None: dir_element = OxmlElement(f'w:{direction}') dir_element.set(qn('w:w'), twips) dir_element.set(qn('w:type'), 'dxa') # dxa表示单位为缇 tcMar.append(dir_element) else: dir_element.set(qn('w:w'), twips) def set_table_cell_margins(table, left=0.05, right=0.05, top=None, bottom=None): """ 设置整个表格所有单元格的边距 参数: table: 表格对象 left: 左边距(厘米),默认为0.05 right: 右边距(厘米),默认为0.05 top: 上边距(厘米),可选 bottom: 下边距(厘米),可选 """ for row in table.rows: for cell in row.cells: set_cell_margins(cell, left, right, top, bottom) def add_formatted_text(paragraph, text): """ 添加带格式的文本到段落中,自动处理斜体、上标、下标和中文双引号 格式规则: - U 和 k 设置为斜体 - rel 设置为下标 - 科学计数法中的指数部分设置为上标 - 中文双引号单独处理并设置中文字体 """ # 定义格式标记的正则表达式 patterns = [ (r'U(rel)?', 'u'), # 匹配U或Urel (r'k=', 'k'), # 匹配k= (r'rel', 'subscript'), # 单独匹配rel (r'%', 'normal'), # 百分号 (r'dB', 'normal'), # dB单位 (r'[“”]', 'quote') # 匹配中文双引号 ] # 位置标记数组 (0=普通, 1=斜体, 3=下标, 4=中文引号) flags = [0] * len(text) # 应用格式标记 for pattern, flag_type in patterns: for match in re.finditer(pattern, text): start, end = match.span() flag_value = { 'u': 1, 'k': 1, 'subscript': 3, 'normal': 0, 'quote': 4 }[flag_type] # 特殊处理Urel组合 if flag_type == 'u' and match.group(1): flags[start] = 1 # U斜体 for i in range(start + 1, end): flags[i] = 3 # rel下标 else: for i in range(start, end): flags[i] = flag_value # 增:手动处理科学计数法格式(避免使用后视断言) for match in re.finditer(r'×10(-\d+)', text): start, end = match.span() # 找到×10后面的指数开始位置 exp_start = match.start(1) # 设置指数部分为上标 for i in range(exp_start, end): flags[i] = 2 # 上标 # 分割并添加格式化的文本片段 start_idx = 0 for i in range(1, len(flags)): if flags[i] != flags[i - 1]: segment = text[start_idx:i] add_segment(paragraph, segment, flags[i - 1]) start_idx = i # 添加最后一段 add_segment(paragraph, text[start_idx:], flags[-1]) def add_segment(paragraph, text, flag): """添加指定格式的文本片段""" if not text: return run = paragraph.add_run(text) run.font.size = Pt(12) # 根据标志设置字体 if flag == 4: # 中文双引号 run.font.name = '宋体' # 设置为中文字体 run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') else: # 其他文本 run.font.name = 'Times New Roman' run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') # 应用其他格式 if flag == 1: # 斜体 (U/k) run.italic = True elif flag == 2: # 上标 (科学计数法指数) run.font.superscript = True elif flag == 3: # 下标 (rel) run.font.subscript = True def excel_sheets_to_word(excel_path, word_path, lieshu,buquedingdu_excel_path): # 加载Excel工作簿 wb = load_workbook(excel_path, data_only=True) bqdd=pd.read_excel(buquedingdu_excel_path) # print(type(bqdd[2000][0])) # 创建/加载Word文档 try: doc = Document(word_path) except: doc = Document() # 文件不存在时创建文档 # 遍历所有sheet sheetn = 0 xuhaon = 0 xuhao = ["二、", "三、", "四、", "五、", "六、", "七、"] # 创建标题样式对象(设置全局行距) title_style = doc.styles.add_style('TitleStyle', WD_STYLE_TYPE.PARAGRAPH) title_style.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE title_style.paragraph_format.line_spacing = 1.5 # 设置为1.5倍行距 panju = 0 measurements =[] for sheet_name in wb.sheetnames: sheet = wb[sheet_name] max_row = sheet.max_row max_col = sheet.max_column # 检测有效数据范围(跳过开头和结尾的空行) start_row = 1 end_row = max_row # 查找第一个非空行(从顶部) for row_idx in range(1, max_row + 1): if any(sheet.cell(row=row_idx, column=col).value for col in range(1, max_col + 1)): start_row = row_idx break # 查找最后一个非空行(从底部) for row_idx in range(max_row, 0, -1): if any(sheet.cell(row=row_idx, column=col).value for col in range(1, max_col + 1)): end_row = row_idx break # print(end_row) if sheet_name=="频率": suoyin="A"+str(end_row) pinlv=sheet[suoyin].value measurements.append(bqdd[pinlv][0]) measurements.append(bqdd[pinlv][1]) zd = lieshu[sheetn] if sheet_name == "相对电平": xuhaon = xuhaon - 1 else: # 创建标题段落并指定样式 title = doc.add_paragraph(style='TitleStyle') title_xu = xuhao[xuhaon] + sheet_name title_run = title.add_run(title_xu) title_run.bold = True # 设置加粗 title_run.font.size = Pt(14) if sheet_name=="调幅深度": measurements.append(bqdd[pinlv][2]) title_zhu = title.add_run("(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)") elif sheet_name=="调频频偏": measurements.append(bqdd[pinlv][3]) title_zhu = title.add_run("(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)") elif sheet_name == "调相相偏": measurements.append(bqdd[pinlv][4]) title_zhu = title.add_run("(功率0dBm,调制速率1kHz,检波器+/-PEAK/2,低通3kHz,高通300Hz)") elif sheet_name == "频谱纯度": measurements.append(bqdd[pinlv][5]) else: title_zhu=title.add_run("") title_zhu.font.size=Pt(10.5) title_zhu.bold=False title.alignment = WD_ALIGN_PARAGRAPH.LEFT # 确保行距设置应用到段落(双重保证) title.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE title.paragraph_format.line_spacing = 1.5 table = doc.add_table(rows=1, cols=zd) # 固定4列 table.style = 'Table Grid' # 添加表头(第一行数据作为标题) header_cells = table.rows[0].cells for col in range(1, zd + 1): # 只取前4列 header_cells[col - 1].text = str(sheet.cell(row=1, column=col).value or "") # 添加数据行(从第二行开始) for row in range(2, end_row + 1): row_cells = table.add_row().cells for col in range(1, zd + 1): # 只取前4列 cell_value = sheet.cell(row=row, column=col).value data_cell = str(cell_value) if cell_value is not None else "" # print(data_cell) if "*" in "9.9999934*": panju="不合格" # print(panju) else: pass data_cell = data_cell.replace("–", "-") data_cell = data_cell.replace("HZ", "Hz") row_cells[col - 1].text = data_cell set_table_cell_margins(table, 0.05, 0.05) # if zd >= 4: # 确保表格至少有4列 # table.columns[3].width = Cm(7) # 索引3对应第4列 # table.autofit = True # print(f"已设置表格 '{sheet_name}' 第4列宽度为7cm(列数={zd})") # else: # print(f"警告:表格 '{sheet_name}' 仅 {zd} 列,无法设置第4列宽度") # 设置单元格居中 for row in table.rows: if zd >= 4: row.cells[3].width = Cm(7) row.height_rule = WD_ROW_HEIGHT_RULE.AUTO # 自动调整行高 for cell in row.cells: cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER for paragraph in cell.paragraphs: paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 设置表格字体 for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') run.font.size = Pt(12) sheetn = sheetn + 1 xuhaon = xuhaon + 1 # print(measurements) if panju=="不合格": measurements.append("注:本次校准结果中标“*”号项目不符合技术指标要求。") else: measurements.append("注:本次校准结果符合技术指标要求。") # 添加带格式的测量数据 for item in measurements: p = doc.add_paragraph(style='TitleStyle') add_formatted_text(p, item) t1=doc.add_paragraph(style='TitleStyle') run_t1 = t1.add_run("以下无内容") run_t1.font.size = Pt(12) run_t1.font.name = 'Times New Roman' # run_t1.font.name = u'黑体' # 中文字体 run_t1._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') run_t1.font.bold = True doc.save(word_path) # 使用示例 excel_path = "信号源数据模板.xlsx" # Excel文件路径 word_path = "信号源原始记录.docx" # 输出Word路径 buquedingdu="不确定度.xlsx" lieshulist=list(pd.read_excel("信号源数据列数.xlsx")["列数"]) excel_sheets_to_word(excel_path, word_path, lieshulist,buquedingdu) print("原始记录或证书出具完毕") input('输入任意字符退出程序……')修改以上代码,使得excel_path 为用鼠标点击的文件"信号源数据模板.xlsx" 。 word_path 为用鼠标点击的文件 "信号源原始记录.docx"
09-03
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值