Spire.Doc 12.3.12 已发布。本次更新新增支持加载、操作 Markdown 文档,以及转换 Word 文档为 Markdown 格式。此外,本次更新还修复了一些已知问题,如转换 Word 为 PDF 后书签不正确的问题。详情请阅读以下内容。
新功能:
Document doc = new Document();
//加载 .md 文件
doc.LoadFromFile("input.md");
//保存为 .md 文件
//doc.SaveToFile("output.md", Spire.Doc.FileFormat.Markdown);
//保存为 .docx 文件
//doc.SaveToFile("output.docx", Spire.Doc.FileFormat.Docx);
//保存为 .doc 文件
//doc.SaveToFile("output.doc", Spire.Doc.FileFormat.Doc);
//保存为 .pdf 文件
doc.SaveToFile("output.pdf", Spire.Doc.FileFormat.PDF);
doc.Close();
Document doc = new Document();
//加载 .docx 文件
doc.LoadFromFile("input.docx");
//加载 .doc 文件
//doc.LoadFromFile("input.doc");
//保存为 .md 文件
doc.SaveToFile("output.md", Spire.Doc.FileFormat.Markdown);
doc.Close();问题修复:
Spire.Office for Java 9.3.1 已正式发布。该版本新增了一些功能,如 Spire.PDF for Java 新增 PdfTextReplacer 类来替换 PDF 文本内容; Spire.XLS for Java 新增 AI 功能; Spire.Presentation for Java 支持在段落中添加数学公式以及获取形状的显示颜色。此外,一些已知问题也在该版本中得到修复。更多新功能及问题修复详情如下。
获取 Spire.Office for Java 9.3.1, 请点击:https://www.e-iceblue.cn/Downloads/Spire-Office-JAVA.html
新功能:
Document document = new Document();
document.loadFromFile(inputFile);
String[] fieldNames = new String[]{"ImageFile"};
String[] fieldValues = new String[]{inputFile_img};
document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
@Override
public void invoke(Object sender, MergeImageFieldEventArgs args) {
mailMerge_MergeImageField(sender, args);
}
};
document.getMailMerge().execute(fieldNames, fieldValues);
document.saveToFile(outputFile, FileFormat.Docx);
private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {
String filePath = field.getImageFileName();
if (filePath != null && !"".equals(filePath)) {
try {
field.setImage(filePath);
field.setImageLink("https://www.baidu.com/");
} catch (Exception e) {
e.printStackTrace();
}
}document.getFieldOptions().setCultureSource(FieldCultureSource.CurrentThread);Document.hasDigitalSignature("filepath");sourceDoc.integrateFontTableTo(Document destDoc);public static void main(String[] args) {
Document document = new Document();
document.HtmlUrlLoadEvent = new MyDownloadEvent();
document.loadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.None);
document.saveToFile(outputFile, FileFormat.PDF);
}
static class MyDownloadEvent extends HtmlUrlLoadHandler {
@Override
public void invoke(Object o, HtmlUrlLoadEventArgs htmlUrlLoadEventArgs) {
try {
byte[] bytes = downloadBytesFromURL(htmlUrlLoadEventArgs.getUrl());
htmlUrlLoadEventArgs.setDataBytes(bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static byte[] downloadBytesFromURL(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置连接超时时间和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
return outputStream.toByteArray();
} else {
throw new Exception("Failed to download content. Response code: " + responseCode);
}
}document.setCustomFonts(InputStream[] fontStreamList);document.clearCustomFonts();Document.setGlobalCustomFonts(InputStream[] fontStreamList);Document.clearGlobalCustomFonts();问题修复:
新功能:
问题修复:
新功能:
PdfDocument doc = new PdfDocument();
doc.loadFromFile("Input.pdf");
PdfPageBase page = doc.getPages().get(0);
PdfTextReplacer textReplacer = new PdfTextReplacer(page);
textReplacer.replaceAllText("old", "NEW");
doc.saveToFile("output.pdf");
doc.dispose();PdfDocument doc = new PdfDocument();
PdfPageBase pdfPage = doc.getPages().add();
List<int[]> inkList = new ArrayList<>();
int[] intPoints = new int[]
{
100,800,
200,800,
200,700
};
inkList.add(intPoints);
PdfInkAnnotation ia = new PdfInkAnnotation(inkList);
ia.setColor(new PdfRGBColor(Color.RED));
ia.getBorder().setWidth(12);
ia.setText("e-iceblue");
((PdfNewPage) pdfPage).getAnnotations().add(ia);
doc.saveToFile("inkannotation.pdf");问题修复:
新功能:
Presentation ppt = new Presentation();
String latexMathCode="x^{2}+\\sqrt{x^{2}+1=2}";
IAutoShape shape=ppt.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE,new Rectangle2D.Float(30,100,400,200));
shape.getTextFrame().getParagraphs().clear();
ParagraphEx p=new ParagraphEx();
shape.getTextFrame().getParagraphs().append(p);
PortionEx portionEx=new PortionEx("Test");
p.getTextRanges().append(portionEx);
p.appendFromLatexMathCode(latexMathCode);
PortionEx portionEx2=new PortionEx("Hello");
p.getTextRanges().append(portionEx2);
ppt.saveToFile(outputFile, FileFormat.AUTO);Presentation ppt = new Presentation();
ppt.loadFromFile("input.pptx");
IAutoShape shape = (IAutoShape)ppt.getSlides().get(0).getShapes().get(0);
System.out.println(shape.getDisplayFill().getFillType().getName());
System.out.println(shape.getDisplayFill().getSolidColor().getColor());问题修复:
直接提取文本已成为从信息密集的 PowerPoint 演示文稿中获取文本信息的重要方法。通过使用 Python 程序,用户可以方便快捷地访问幻灯片中的内容,从而高效地收集信息并进一步处理数据。在本文中,您将学习如何使用 Spire.Presentation for Python 在 Python 中提取 PowerPoint 演示文稿的文本,包括幻灯片、演讲者备注和注释中的文本。
本教程需要用到 Spire.Presentation for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Presentation
如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.Presentation for Python
PowerPoint 演示幻灯片中的文本被放置在形状中。因此,开发人员可以通过访问每张幻灯片中的所有形状并提取其中包含的文本来提取演示文稿中的文本。具体步骤如下:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个Presentation对象
presentation = Presentation()
# 加载PPTX文件
presentation.LoadFromFile("输入文档.pptx")
# 用于存储文本内容的列表
text = []
# 遍历每一页幻灯片
for slide in presentation.Slides:
# 遍历每个形状
for shape in slide.Shapes:
# 判断形状是否是IAutoShape
if isinstance(shape, IAutoShape):
# 遍历每个段落并获取文本内容
for paragraph in (shape if isinstance(shape, IAutoShape) else None).TextFrame.Paragraphs:
text.append(paragraph.Text)
# 将文本内容写入到文件中
with open("幻灯片文本.txt", "w", encoding='utf-8') as f:
for s in text:
f.write(s + "\n")
# 释放Presentation对象
presentation.Dispose()

演讲者备注是为演讲者提供指导的附加信息,听众看不到。每张幻灯片的发言人备注中的文本都存储在备注幻灯片中,开发人员可以通过 NotesSlide.NotesTextFrame.Text 属性提取文本。提取发言人注释中文本的详细步骤如下:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个Presentation对象
pres = Presentation()
# 从输入文件加载Presentation对象
pres.LoadFromFile("输入文档.pptx")
# 创建一个空列表用于存储演讲者备注文本
list = []
# 遍历每一页幻灯片
for slide in pres.Slides:
# 获取当前幻灯片的备注页
notesSlide = slide.NotesSlide
# 获取备注页中的文本内容
notes = notesSlide.NotesTextFrame.Text
# 将备注文本添加到列表中
list.append(notes)
# 打开一个文本文件用于写入演讲者备注文本
f = open("演讲者备注文本.txt", "w", encoding="utf-8")
# 将演讲者备注文本写入文件
for note in list:
f.write(note)
f.write("\n")
# 关闭文件
f.close()
# 释放Presentation对象
pres.Dispose()

使用 Spire.Presentation for Python,开发人员还可以从 PowerPoint 演示文稿的注释中提取文本,方法是使用 ISlide.Comments 属性从幻灯片中获取注释,并使用 Comment.Text 属性从注释中检索文本。具体步骤如下:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个Presentation对象
presentation = Presentation()
# 加载PPTX文件
presentation.LoadFromFile("输入文档.pptx")
# 用于存储注释内容的列表
comment_list = []
# 遍历每一页幻灯片
for slide in presentation.Slides:
# 获取当前幻灯片的所有注释
comments = slide.Comments
# 遍历每条注释并提取注释文本
for comment in comments:
comment_text = comment.Text
comment_list.append(comment_text)
# 将注释内容写入到文件中
with open("注释文本.txt", "w", encoding="utf-8") as f:
for comment in comment_list:
f.write(comment + "\n")
# 释放Presentation对象
presentation.Dispose()

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
Spire.PDF for Java 10.3.4 已发布。本次更新新增 PdfTextReplacer 类来替换 PDF 文本内容,同时支持为 PDF 添加 InkAnnotation。此外,该版本还优化了 PDF 数字签名时间同系统本地时间。详情请阅读以下内容。
新功能:
PdfDocument doc = new PdfDocument();
doc.loadFromFile("Input.pdf");
PdfPageBase page = doc.getPages().get(0);
PdfTextReplacer textReplacer = new PdfTextReplacer(page);
textReplacer.replaceAllText("old", "NEW");
doc.saveToFile("output.pdf");
doc.dispose();PdfDocument doc = new PdfDocument();
PdfPageBase pdfPage = doc.getPages().add();
List<int[]> inkList = new ArrayList<>();
int[] intPoints = new int[]
{
100,800,
200,800,
200,700
};
inkList.add(intPoints);
PdfInkAnnotation ia = new PdfInkAnnotation(inkList);
ia.setColor(new PdfRGBColor(Color.RED));
ia.getBorder().setWidth(12);
ia.setText("e-iceblue");
((PdfNewPage) pdfPage).getAnnotations().add(ia);
doc.saveToFile("inkannotation.pdf");问题修复:
Spire.XLS for Java 14.3.2 已发布。本次更新优化了解析 Excel 文档时的内存占用。此外,本次更新还修复了一些已知问题,如复制 worksheet 表后形状丢失的问题。详情请阅读以下内容。
问题修复:
在 PowerPoint 中管理文档属性是创建演示文稿的一个重要方面。这些属性可作为元数据,提供有关文件的重要信息,如作者、主题和关键字。通过添加、检索或删除文档属性,用户可以控制演示文稿的组织和定制。无论是添加相关标签以方便分类、访问作者详细信息,还是删除敏感数据,在 PowerPoint 中有效管理文档属性都能确保无缝协作和幻灯片演示的专业性。
在本文中,您将学习如何使用 Spire.Presentation for Python 在 Python 中添加、读取和删除 PowerPoint 文件中的文档属性。
本教程需要用到 Spire.Presentation for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Presentation
如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.Presentation for Python
文档属性可分为两种类型:标准文档属性和自定义文档属性。
Spire.Presentation for Python 提供的 DocumentProperty 类可同时处理标准文档属性和自定义文档属性。标准文档属性可通过 DocumentProperty 类的 标题、主题、作者、经理、公司 等属性访问。要添加或检索自定义属性,可以使用 DocumentProperty 类的 set_Item() 方法和 GetPropertyName() 方法。
要添加或更改标准文档属性,您可以为 DocumentProperty.Title 属性、DocumentProperty.Subject 属性和其他类似属性赋值。要在演示文稿中添加自定义属性,请使用 DocumentProperty.set_Item(name: str, value: SpireObject) 方法。具体步骤如下:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个新的Presentation对象
presentation = Presentation()
# 从指定的文件加载演示文稿
presentation.LoadFromFile("输入文档.pptx")
# 获取演示文稿的文档属性对象
documentProperty = presentation.DocumentProperty
# 设置演示文稿的标题
documentProperty.Title = "年度销售简报"
# 设置演示文稿的主题
documentProperty.Subject = "公司业绩和销售策略"
# 设置演示文稿的作者
documentProperty.Author = "张三"
# 设置演示文稿的经理
documentProperty.Manager = "李四"
# 设置演示文稿的公司
documentProperty.Company = "冰蓝科技公司"
# 设置演示文稿的类别
documentProperty.Category = "业务"
# 设置演示文稿的关键词
documentProperty.Keywords = "销售,战略,业绩"
# 设置演示文稿的备注
documentProperty.Comments = "请在周五之前审核并提供反馈"
# 设置自定义文档属性:文档ID
documentProperty.set_Item("文档ID", Int32(12))
# 设置自定义文档属性:授权人
documentProperty.set_Item("授权人", String("产品经理"))
# 设置自定义文档属性:授权日期
documentProperty.set_Item("授权日期", DateTime(2024, 3, 20, 0, 0, 0, 0))
# 将修改后的演示文稿保存到新文件中
presentation.SaveToFile("属性.pptx", FileFormat.Pptx2019)
presentation.Dispose()

DocumentProperty.Title 和类似属性不仅用于设置标准属性,还可以返回标准属性的值。由于自定义属性的名称不是恒定的,我们需要使用 DocumentProperty.GetPropertyName(index: int) 方法来获取名称。然后,我们可以使用 DocumentProperty.get_Item(name: str) 方法获取属性值。
读取 PowerPoint 文件属性的步骤如下:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个新的Presentation对象
presentation = Presentation()
# 从指定文件加载演示文稿
presentation.LoadFromFile("属性.pptx")
# 获取演示文稿的文档属性对象
documentProperty = presentation.DocumentProperty
# 打印文档属性中的标题
print("标题: " + documentProperty.Title)
# 打印文档属性中的主题
print("主题:" + documentProperty.Subject)
# 打印文档属性中的作者
print("作者: " + documentProperty.Author)
# 打印文档属性中的经理
print("经理:" + documentProperty.Manager)
# 打印文档属性中的公司
print("公司: " + documentProperty.Company)
# 打印文档属性中的类别
print("类别: " + documentProperty.Category)
# 打印文档属性中的关键字
print("关键字:" + documentProperty.Keywords)
# 打印文档属性中的评论
print("评论: " + documentProperty.Comments)
# 获取自定义文档属性的数量
count = documentProperty.Count
# 遍历所有自定义文档属性
for i in range(count):
# 获取自定义文档属性的名称
customPropertyName = documentProperty.GetPropertyName(i)
# 获取自定义文档属性的值
customPropertyValue = documentProperty.get_Item(customPropertyName)
# 打印自定义文档属性的名称和值
print(customPropertyName + ": " + str(customPropertyValue))

删除标准属性意味着给一个属性(如 DocumentProperty.Title)赋值一个空字符串。要移除自定义属性,Spire.Presentation 提供了 DocumentProperty.Remove(name: str) 方法。以下是用 Python 从 PowerPoint 文件中移除文档属性的步骤:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个新的Presentation对象
presentation = Presentation()
# 从指定文件加载演示文稿
presentation.LoadFromFile("属性.pptx")
# 获取演示文稿的文档属性对象
documentProperty = presentation.DocumentProperty
# 清空默认文档属性中的内容
documentProperty.Title = ""
documentProperty.Subject = ""
documentProperty.Author = ""
documentProperty.Manager = ""
documentProperty.Company = ""
documentProperty.Category = ""
documentProperty.Keywords = ""
documentProperty.Comments = ""
# 获取自定义文档属性的数量
i = documentProperty.Count
# 逐个删除自定义文档属性
while i > 0:
# 获取自定义文档属性的名称
customPropertyName = documentProperty.GetPropertyName(i - 1)
# 移除指定名称的自定义文档属性
documentProperty.Remove(customPropertyName)
i = i - 1
# 将修改后的演示文稿保存到新文件中
presentation.SaveToFile("删除属性.pptx", FileFormat.Pptx2019)
presentation.Dispose()

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
在 Word 文档中,当页眉页脚的内容过多时,我们可以调整其高度以便完整的显示其内容;当其他文档需要相同的页眉页脚时,我们可以直接复制页眉页脚到想用的文档,这样可以保证页眉页脚的内容和样式等一致;当打印时需要节省打印纸的空间或共享文档时需要避免隐秘信息被公开,我们可以删除页眉页脚。在本文中,我们将介绍如何使用 Spire.Doc for Python 在 Python 中调整、复制或删除 Word 文档的页眉页脚。
本教程需要 Spire.Doc for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Doc
如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.Doc for Python
Spire.Doc for Python 提供了 Section.PageSetup.HeaderDistance 和 Section.PageSetup.FooterDistance 属性来设置 Word 文档的页眉和页脚的高度,这两个属性的值的单位是磅(pt)。以下是详细步骤:
from spire.doc import *
from spire.doc.common import *
# 定义输入和输出文件名
inputFile = "页眉页脚.docx"
outputFile = "调整页眉页脚高度.docx"
# 创建一个文档对象
doc = Document()
# 从文件加载文档
doc.LoadFromFile(inputFile)
# 获取文档的第一个节(section)
section = doc.Sections.get_Item(0)
# 调整页眉和页脚的高度为100
section.PageSetup.HeaderDistance = 100
section.PageSetup.FooterDistance = 100
# 将修改后的文档保存到新文件中
doc.SaveToFile(outputFile, FileFormat.Docx)
doc.Close()

Spire.Doc for Python 提供了 Section.PageSetup.PageBorderIncludeHeader 和 Section.PageSetup.PageBorderIncludeFooter 属性来设置页面边框是否包含页眉页脚。以下是详细步骤:
from spire.doc import *
from spire.doc.common import *
# 定义输出文件名
outputFile = "页面边框环绕.docx"
# 创建一个文档对象
doc = Document()
# 添加一个节(section)
section = doc.AddSection()
# 设置页面边框样式为波浪线
section.PageSetup.Borders.BorderType(BorderStyle.Wave)
section.PageSetup.Borders.Color(Color.get_Green())
section.PageSetup.Borders.Left.Space = 20.0
section.PageSetup.Borders.Right.Space = 20.0
# 添加页眉
paragraph1 = section.HeadersFooters.Header.AddParagraph()
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right
headerText = paragraph1.AppendText("页眉未包含在页面边框中")
headerText.CharacterFormat.FontName = "宋体"
headerText.CharacterFormat.FontSize = 20.0
headerText.CharacterFormat.Bold = True
# 添加页脚
paragraph2 = section.HeadersFooters.Footer.AddParagraph()
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left
footerText = paragraph2.AppendText("页脚包含在页面边框中")
footerText.CharacterFormat.FontName = "微软雅黑"
footerText.CharacterFormat.FontSize = 20.0
footerText.CharacterFormat.Bold = True
# 设置页面边框不包含页眉,设置页眉距离为40,页面边框包含页脚,设置页脚距离为40
section.PageSetup.PageBorderIncludeHeader = False
section.PageSetup.HeaderDistance = 40.0
section.PageSetup.PageBorderIncludeFooter = True
section.PageSetup.FooterDistance = 40.0
# 将文档保存到文件
doc.SaveToFile(outputFile, FileFormat.Docx)
doc.Close()

当您创建多个密切相关的 Word 文档时,您可能希望将其中一个文档的页眉或页脚用作其他文档的页眉或页脚。例如,在创建内部文档时,将公司徽标、名称或其他材料放在页眉中,这时只需创建一次页眉,然后将页眉复制到其他地方即可。详细的实现步骤如下:
from spire.doc import *
from spire.doc.common import *
# 定义输入和输出文件名
inputFile = "页眉页脚.docx"
inputFile_1 = "示例文档.docx"
outputFile = "复制页眉页脚.docx"
# 创建两个文档对象并加载文档
doc1 = Document()
doc1.LoadFromFile(inputFile)
header = doc1.Sections.get_Item(0).HeadersFooters.Header
footer = doc1.Sections.get_Item(0).HeadersFooters.Footer
doc2 = Document()
doc2.LoadFromFile(inputFile_1)
# 复制页眉
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
for h in range(header.ChildObjects.Count):
obj = header.ChildObjects.get_Item(h)
section.HeadersFooters.Header.ChildObjects.Add(obj.Clone())
# 复制页脚
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
for f in range(footer.ChildObjects.Count):
obj = footer.ChildObjects.get_Item(f)
section.HeadersFooters.Footer.ChildObjects.Add(obj.Clone())
# 将修改后的文档保存到新文件中
doc2.SaveToFile(outputFile, FileFormat.Docx)
doc2.Close()

Word 文档的页眉页脚内容可能会包含作者姓名、文档用途等隐秘信息,当共享文档或打印文档时可能需要删除这些内容以保护隐私或节省打印纸的空间。删除页眉页脚内容的详细步骤如下:
from spire.doc import *
from spire.doc.common import *
# 定义输入和输出文件名
inputFile = "页眉页脚.docx"
outputFile = "删除页眉页脚.docx"
# 创建一个文档对象
doc = Document()
# 从文件加载文档
doc.LoadFromFile(inputFile)
# 获取文档的第一个节(section)
section = doc.Sections[0]
# 清空第一页、奇数页和偶数页的页眉
header = None
header = section.HeadersFooters[HeaderFooterType.HeaderFirstPage]
if header is not None:
header.ChildObjects.Clear()
header = section.HeadersFooters[HeaderFooterType.HeaderOdd]
if header is not None:
header.ChildObjects.Clear()
header = section.HeadersFooters[HeaderFooterType.HeaderEven]
if header is not None:
header.ChildObjects.Clear()
# 清空第一页、奇数页和偶数页的页脚
footer = None
footer = section.HeadersFooters[HeaderFooterType.FooterFirstPage]
if footer is not None:
footer.ChildObjects.Clear()
footer = section.HeadersFooters[HeaderFooterType.FooterOdd]
if footer is not None:
footer.ChildObjects.Clear()
footer = section.HeadersFooters[HeaderFooterType.FooterEven]
if footer is not None:
footer.ChildObjects.Clear()
# 将修改后的文档保存到新文件中
doc.SaveToFile(outputFile, FileFormat.Docx)
doc.Close()
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
PowerPoint 中的柱形图是一种利用柱形或条形来展示不同类别间数据对比的图形化数据表示方式。它常用于展现财务数据、统计资料以及其他定量信息。每个柱形代表一个类别,其高度与该类别的数值相对应。柱状图在 PowerPoint 中易于创建与自定义,使得用户能够快速将数据可视化。
在本文中,您将学习如何使用 Spire.Presentation for Python 在 Python 中给 PowerPoint 文档创建柱形图。
本教程需要 Spire.Presentation for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。
pip install Spire.Presentation
如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.Presentation for Python
簇状柱形图是一种柱形图变体,其中柱形(或条形)被分组为若干簇或段,每个簇代表一个类别,而该簇内各柱形的高度则反映该类别对应数据点的数值。
使用 Spire.Presentation for Python 库在 PowerPoint 中添加簇状柱形图,可调用 ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool) 方法,并将图表类型指定为 ColumnClustered。此方法会返回一个 IChart 类的对象,利用该对象可以设置图表数据、标题、系列标签、类别标签、系列值及其他属性。
以下是使用 Python 在 PowerPoint 中创建簇状柱形图的步骤:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个Presentation对象
presentation = Presentation()
# 设置幻灯片尺寸类型
presentation.SlideSize.Type = SlideSizeType.Screen16x9
# 获取第一张幻灯片
slide = presentation.Slides[0]
# 添加簇状柱形图
rect = RectangleF.FromLTRB(40, 80, 700, 450)
chart = slide.Shapes.AppendChartInit(ChartType.ColumnClustered, rect, False)
# 设置图表标题
chart.ChartTitle.TextProperties.Text = "销售情况"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 25
chart.HasTitle = True
# 向图表插入文本作为系列标签
chart.ChartData[0,0].Text = "产品名"
chart.ChartData[0,1].Text = "Product A"
chart.ChartData[0,2].Text = "Product B"
# 向图表插入文本作为类别标签
chart.ChartData[1,0].Text = "第一季度"
chart.ChartData[2,0].Text = "第二季度"
chart.ChartData[3,0].Text = "第三季度"
chart.ChartData[4,0].Text = "第四季度"
# 向图表插入数字作为系列值
Series1 = [35000, 46000, 28000, 52000]
Series2 = [41000, 32000, 36000, 40000]
i = 0
while i < len(Series1):
chart.ChartData[i + 1,1].NumberValue = Series1[i]
chart.ChartData[i + 1,2].NumberValue = Series2[i]
i += 1
# 设置系列标签
chart.Series.SeriesLabel = chart.ChartData["B1","C1"]
# 设置类别标签
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]
# 设置系列的值
chart.Series[0].Values = chart.ChartData["B2","B5"]
chart.Series[1].Values = chart.ChartData["C2","C5"]
# 设置柱间宽度
chart.GapWidth = 350
# 设置系列重叠程度
chart.OverLap = -50
# 设置每个系列的填充颜色
chart.Series[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].Fill.SolidColor.Color = Color.get_CadetBlue()
chart.Series[1].Fill.FillType = FillFormatType.Solid
chart.Series[1].Fill.SolidColor.Color = Color.get_LightBlue()
# 添加数据标签
for i in range(len(Series1)):
chart.Series[0].DataLabels.Add()
chart.Series[1].DataLabels.Add()
# 保存文档
presentation.SaveToFile("簇状柱形图.pptx", FileFormat.Pptx2019)
# 关闭对象
presentation.Dispose()

堆积柱形图是标准柱形图的一种变体,其中每一根柱子代表一个类别,柱子的高度对应于该类别的总值。
使用 Spire.Presentation for Python 库在 PowerPoint 中添加堆积柱形图时,您需要调用 ISlide.Shapes.AppendChartInit(type: ChartType, rectangle RectangleF, init bool) 方法,并将图表类型指定为 ColumnStacked。接下来,您可以使用 IChart 类的属性来设置图表数据、标题、系列标签、类别标签、系列值及其他属性。
以下是使用 Python 在 PowerPoint 中创建堆积柱状图的步骤:
from spire.presentation.common import *
from spire.presentation import *
# 创建一个Presentation对象
presentation = Presentation()
# 设置幻灯片尺寸类型
presentation.SlideSize.Type = SlideSizeType.Screen16x9
# 获取第一张幻灯片
slide = presentation.Slides[0]
# 添加堆积柱形图
rect = RectangleF.FromLTRB(40, 80, 700, 450)
chart = slide.Shapes.AppendChartInit(ChartType.ColumnStacked, rect, False)
# 设置图表标题
chart.ChartTitle.TextProperties.Text = "销售情况"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 25
chart.HasTitle = True
# 向图表插入文本作为系列标签
chart.ChartData[0,0].Text = "产品名"
chart.ChartData[0,1].Text = "Product A"
chart.ChartData[0,2].Text = "Product B"
# 向图表插入文本作为类别标签
chart.ChartData[1,0].Text = "第一季度"
chart.ChartData[2,0].Text = "第二季度"
chart.ChartData[3,0].Text = "第三季度"
chart.ChartData[4,0].Text = "第四季度"
# 向图表插入数字作为系列值
Series1 = [35000, 46000, 28000, 52000]
Series2 = [41000, 32000, 36000, 40000]
i = 0
while i < len(Series1):
chart.ChartData[i + 1,1].NumberValue = Series1[i]
chart.ChartData[i + 1,2].NumberValue = Series2[i]
i += 1
# 设置系列标签
chart.Series.SeriesLabel = chart.ChartData["B1","C1"]
# 设置类别标签
chart.Categories.CategoryLabels = chart.ChartData["A2","A5"]
# 设置系列的值
chart.Series[0].Values = chart.ChartData["B2","B5"]
chart.Series[1].Values = chart.ChartData["C2","C5"]
# 设置柱间宽度
chart.GapWidth = 350
# 设置每个系列的填充颜色
chart.Series[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].Fill.SolidColor.Color = Color.get_CadetBlue()
chart.Series[1].Fill.FillType = FillFormatType.Solid
chart.Series[1].Fill.SolidColor.Color = Color.get_LightBlue()
# 添加数据标签
for i in range(len(Series1)):
chart.Series[0].DataLabels.Add()
chart.Series[1].DataLabels.Add()
# 保存文档
presentation.SaveToFile("堆积柱形图.pptx", FileFormat.Pptx2019)
# 关闭对象
presentation.Dispose()

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
Spire.Office 9.3.1 已发布。在该版本中,Spire.Doc 支持解析 Word 文档中的 GIF 格式内容;Spire.XLS 支持数据透视表分组功能;Spire.Presentation 新增 AI 功能并支持设置 PPTX 转 SVG 的转换选项;Spire.DocViewer 支持 WPF 和 MAUI 平台;Spire.PDFViewer 支持获取鼠标点击时相对于 PDF 页面内容的坐标。此外,许多已知问题也在该版本中成功修复。详情请阅读以下内容。
该版本涵盖了最新版的 Spire.Doc,Spire.PDF,Spire.XLS,Spire.Email,Spire.DocViewer,Spire.PDFViewer,Spire.Presentation,Spire.Spreadsheet,Spire.OfficeViewer,Spire.Barcode,Spire.DataExport。
版本信息如下:
https://www.e-iceblue.cn/Downloads/Spire-Office-NET.html
新功能:
问题修复:
新功能:
XlsPivotTable pt = worksheet.PivotTables[0] as XlsPivotTable;
IPivotField field = pt.RowFields[0];
DateTime start = new DateTime(2024, 5, 6);
DateTime end = new DateTime(2024, 10, 6);
PivotGroupByTypes[] types = new PivotGroupByTypes[]{ PivotGroupByTypes.Days };
field.CreateGroup(start, end, types, 1);Workbook workbook = new Workbook();
workbook.LoadFromFile(@"test.xlsx");
Worksheet sheet = workbook.Worksheets[0];
sheet.Range["A1"].FindAll()foreach (XlsPivotTable pt in wb.Worksheets["PivotTable"].PivotTables)
{
pt.Options.RepeatAllItemLabels = true;
}问题修复:
问题修复:
新功能:
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
IAutoShape shape = presentation.Slides[0].Shapes[0] as IAutoShape;
DefaultTextRangeProperties format = shape.TextFrame.Paragraphs[0].TextRanges[0].DisPlayFormat;
File.AppendAllText(outputFile, "text :" + shape.TextFrame.Paragraphs[0].TextRanges[0].Text + "\r\n");
File.AppendAllText(outputFile, "is bold :" + format.IsBold + "\r\n");
File.AppendAllText(outputFile, "is italic :" + format.IsItalic + "\r\n");Presentation ppt = new Presentation();
ppt.LoadFromFile(inputFile);
ppt.SaveToSvgOption.SaveUnderlineAsDecoration = true;
byte[] svgByte = ppt.Slides[0].Shapes[0].SaveAsSvgInSlide();
FileStream fs = new FileStream(outputFile + "1.svg", FileMode.Create);
fs.Write(svgByte, 0, svgByte.Length);
fs.Close();Presentation presentation = new Presentation();
presentation.LoadFromFile(@"in.pptx");
bool showMasterShape = presentation.Slides[1].Layout.ShowMasterShapes;问题修复:
主要 AI 功能及对应的 API:
| 功能 | API |
| 文本润色 | public string Polish(IShape shape, string language); |
| 翻译 | public string Translate(ISlide slide, string language); |
| 总结 | public string Summarize(IShape shape, string language); |
| 幻灯片生成 | public Presentation Generate(string describe, string language, bool genareteBackGroundImage); |
| 提问 | public string Ask(string question, bool enableHistory = false); |
| 文档搜索 | public string DocumentSearch(string question, string file_server_path, bool enableHistory = false); |
| 图片生成 | public Stream ImageGenerate(string description); |
新功能:
新功能:
private void Form1_Load(object sender, EventArgs e)
{
this.pdfDocumentViewer1.LoadFromFile("1.pdf");
this.pdfDocumentViewer1.MouseDown += new MouseEventHandler(PV_Click);
}
private void PV_Click(object sender, MouseEventArgs e)
{
string outputFile = "out.Pdf";
string outputFile_TXT = "out.txt";
File.Delete(outputFile_TXT);
if (e.Button == MouseButtons.Left)
{
PointF[] controlPositions = new PointF[] { e.Location};
Spire.PdfViewer.Forms.PagePosition[] pagePositions = this.pdfDocumentViewer1.ControlToPage(controlPositions);
string fileName = this.pdfDocumentViewer1.FileName;
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(fileName,FileFormat.PDF);
PdfPageBase page = doc.Pages[pagePositions[0].PageIndex];
RectangleF bounds = new RectangleF(pagePositions[0].Position, new SizeF(100, 100));
PdfTextExtractor textExtractor = new PdfTextExtractor(page);
PdfTextExtractOptions option = new PdfTextExtractOptions();
option.ExtractArea = bounds;
string text = textExtractor.ExtractText(option);
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
PdfTextWidget pdfTextbox = new PdfTextWidget();
pdfTextbox.Font = font;
pdfTextbox.Brush = PdfBrushes.Red;
pdfTextbox.Text = "stamp";
pdfTextbox.Draw(page, bounds);
doc.Pages[pagePositions[0].PageIndex].Canvas.DrawRectangle(PdfPens.Red, bounds);
doc.SaveToFile(outputFile);
File.AppendAllText(outputFile_TXT, "Position: " + pagePositions[0].Position.ToString() + "\ntext:\r\n " + text);
MessageBox.Show("finish");
doc.Dispose();
}
}Spire.Presentation for Java 9.3.1 已发布。该版本支持在段落中添加数学公式以及获取形状的显示颜色。此外,合并文档时程序抛“DocumentEditException”异常的问题也已成功修复。详情请查看以下内容。
新功能:
Presentation ppt = new Presentation();
String latexMathCode="x^{2}+\\sqrt{x^{2}+1=2}";
IAutoShape shape=ppt.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE,new Rectangle2D.Float(30,100,400,200));
shape.getTextFrame().getParagraphs().clear();
ParagraphEx p=new ParagraphEx();
shape.getTextFrame().getParagraphs().append(p);
PortionEx portionEx=new PortionEx("Test");
p.getTextRanges().append(portionEx);
p.appendFromLatexMathCode(latexMathCode);
PortionEx portionEx2=new PortionEx("Hello");
p.getTextRanges().append(portionEx2);
ppt.saveToFile(outputFile, FileFormat.AUTO);Presentation ppt = new Presentation();
ppt.loadFromFile("input.pptx");
IAutoShape shape = (IAutoShape)ppt.getSlides().get(0).getShapes().get(0);
System.out.println(shape.getDisplayFill().getFillType().getName());
System.out.println(shape.getDisplayFill().getSolidColor().getColor());问题修复:
https://www.e-iceblue.cn/Downloads/Spire-Presentation-JAVA.html