/创建一个winform窗体,输入路径来获取word文件中的图片/
1.首先需要下载spire组件,两种办法
方法一
PM后直接输入要引用的就可以。
缺点:必须知道要引入的组件名,所以建议第二种方法
方法二
右击项目选择管理解决方案NuGet程序包
直接搜索就好
我们引入Spire包:
2.在using指令添加:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
完善界面:
3.提取路径(输入路径):
private void text_click(object sender, EventArgs e)
{
//弹出一个选择目录的对话框
OpenFileDialog file = new OpenFileDialog();
file.Multiselect = true;
file.ShowDialog();
file.Filter = "所有文件(*doc*)|*.doc*";
textBox1.Text = file.FileName;
}
4.保存路径:
private void text_click_2(object sender, EventArgs e)
{
FolderBrowserDialog path = new FolderBrowserDialog();
path.ShowDialog();
textBox2.Text = path.SelectedPath;
}
5.核心设计思路:扫描文件来找到图片,每找到一次就存储一次
private void button1_Click(object sender, EventArgs e)
{
Document document = new Document (@textBox1.Text, FileFormat.Docx);//路径添加?
int index = 0;
//获取文档的section
foreach (Section section in document.Sections)
{
//获取section中的段落
foreach (Paragraph paragraph in section.Paragraphs)
{
//获取段落中的文档对象
foreach (DocumentObject docObject in paragraph.ChildObjects)
{
//对对象的type进行判断,如果是图片,就提取出来
if (docObject.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObject as DocPicture;
//给图片命名
String imageName = String.Format(@"\Image-{0}.png", index);
imageName = @textBox2.Text + imageName;
//保存图片
picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
index++;
}
}
}
}
MessageBox.Show("提取成功");
}
提取成功: