革新文档管理:使用多种编程语言从 Word 中提取 Excel 附件和文件名

当我们在处理Microsoft Word文档时,经常会遇到嵌入了Excel附件的情况。在这种情况下,我们可能需要提取嵌入式Excel文件并将其保存为单独的文件。在本文中,我们将探讨如何使用Python、Java、JavaScript、Go、C#和C++来提取Word文档中的Excel附件并识别文件名保存。

目录

一、提取Word文档中的Excel附件

二、利用Python脚本提取Word中的Excel表格

1、安装Python和相关库

2、Python程序实现

三、通过Java提取Word中的Excel表格

四、通过JavaScript提取Word中的Excel表格

五、通过 go实现提取Word文档中的Excel附件并识别文件名保存

六、通过 c#和c++实现提取Word文档中的Excel附件并识别文件名保存


一、提取Word文档中的Excel附件

在Word文档中,我们会经常插入一些Excel表格,这些表格附件是包含在Word文档中的。要提取Word文档中的Excel附件并识别文件名保存,我们需要执行以下步骤:

1、打开Word文档并切换到“文件”菜单,在“文件”菜单中选择“另存为”选项。

2、在弹出的另存为菜单中,选择“单个网页(.htm,.html)”后另存为一个htm文件。

3、打开生成的htm文件,找到包含Excel附件的链接。

4、通过右键点击Excel附件链接并选择“另存为”选项,将Excel表格下载到本地计算机中,同样可以使用python脚本来实现。

二、利用Python脚本提取Word中的Excel表格

Python是一种很强大的编程语言,它为我们提供了许多方便的工具和库。在Python中,我们可以使用docx、xlrd、xlsxwriter等常用库来实现从Word文档提取Excel表格并进行文件名读取和保存的功能。

1、安装Python和相关库

在开始使用Python程序之前,我们需要先安装Python和相关库。在Python官网中,您可以下载最新的Python安装程序并安装在您的计算机上。在安装完成后,您可以使用pip工具来安装所需的库,其中包括docx、xlrd、xlsxwriter等库。

2、Python程序实现

在Python中,我们可以使用docx、xlrd、xlsxwriter等库来实现从Word文档提取Excel表格并进行文件名读取和保存的功能。一个用Python编写的样例程序如下所示:

import os
from docx import Document                   
import xlrd, xlwt                         

def get_excel_name(path):
    workbook = xlrd.open_workbook(path)
    names = workbook.sheet_names()
    return names[0]

def extract_excel(filename):
    doc = Document(filename)
    for obj in doc.inline_shapes:
        if obj.type == 3:                   
            info = obj._inline._element[0][0][1].attrib            
            r_id = info.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id')
            part = obj.part.related_parts[r_id]
            excel_file = part.blob                    
            name = get_excel_name(part.partname)          
            with open(name + ".xlsx", 'wb') as f:
                f.write(excel_file)
                print("Successfully extract" + name + ".xlsx!")
            
if __name__ == '__main__':
    extract_excel("test.docx")

在实现中,我们首先通过使用xlrd库来读取所处理的Excel表格的文件名,然后利用docx库来提取Word文档中的表格附件,最后使用Python内置的with关键字来保存这些附件,并以正确的文件名命名。


三、通过Java提取Word中的Excel表格

在Java中可以使用Apache POI库来提取Word文档中的Excel附件并识别文件名保存。以下是代码示例:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExtractExcelFromWord {
    public static void main(String[] args) throws Exception {
        String wordFilePath = "path/to/word/file.docx";
        String excelSaveDirPath = "path/to/excel/save/dir";

        InputStream wordIS = new FileInputStream(wordFilePath);
        OPCPackage opc = OPCPackage.open(wordIS);
        PackageRelationshipCollection prc = opc.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject");

        // Iterate over each embedded object and extract Excel file
        for (Iterator it = prc.iterator(); it.hasNext();) {
            PackageRelationship pr = (PackageRelationship) it.next();
            if (pr.getTargetMode() == TargetMode.INTERNAL) {
                PackagePart pp = opc.getPart(pr.getTargetURI());
                String contentType = pp.getContentType();
                if (contentType.contains("excel")) {
                    String excelFileName = pr.getTargetURI().toString().substring(pr.getTargetURI().toString().lastIndexOf('/') + 1);
                    excelFileName = excelFileName.replaceAll("%20", " ");
                    OutputStream os = new FileOutputStream(excelSaveDirPath + "/" + excelFileName);
                    os.write(pp.getByteArray());
                    os.close();
                }
            }
        }

        // Close resources
        opc.close();
        wordIS.close();
    }
}

以上代码通过打开Word文件并获取包含Excel附件的PackageRelationshipCollection。然后针对每个PackageRelationship检查其目标类型是否是“application/vnd.ms-excel”,如果是则提取Excel附件到指定目录,并使用URI的最后一部分作为Excel文件名。


四、通过JavaScript提取Word中的Excel表格

在JavaScript中,可以使用JSZip库来提取Word文档中的Excel附件并识别文件名保存。以下是代码示例:

var wordFilePath = "path/to/word/file.docx";
var excelSaveDirPath = "path/to/excel/save/dir";
var zip = new JSZip();

// Load Word document
JSZipUtils.getBinaryContent(wordFilePath, function(err, content) {
  if (err) {
    throw err;
  }

  // Extract Excel files from Word document
  zip.loadAsync(content).then(function(zip) {
    Object.keys(zip.files).forEach(function(filename) {
      if (filename.indexOf("word/embeddings/") === 0 && filename.indexOf(".xlsx") !== -1) {
        var excelFile = zip.file(filename);
        var excelFileName = filename.substring(filename.lastIndexOf("/") + 1);
        excelFileName = excelFileName.replaceAll("%20", " ");
        excelFile.async("blob").then(function(excelBlob) {
          var excelSavePath = excelSaveDirPath + "/" + excelFileName;
          saveAs(excelBlob, excelSavePath);
        });
      }
    });
  });
});

以上代码通过加载Word文档,并使用JSZip库提取包含Excel附件的压缩文件。然后,针对每个Excel文件的文件名检查是否符合条件(位于“word/embeddings/”目录下并以“.xlsx”结尾)。如果是,则提取Excel文件,并使用文件名保存到指定路径中。由于JSZip的异步加载特性,需要使用Promise来确保在提取Excel文件后进行保存。

请注意,上面的代码中使用了FileSaver.js库来在浏览器中保存文件。如果您使用的是Node.js环境,则应该使用fs模块来保存文件。

五、通过 go实现提取Word文档中的Excel附件并识别文件名保存

在Golang中,可以使用go-zip库来提取Word文档中的Excel附件并识别文件名保存。以下是代码示例:

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
    "path/filepath"
    "strings"
)

func main() {
    wordFilePath := "path/to/word/file.docx"
    excelSaveDirPath := "path/to/excel/save/dir"

    r, err := zip.OpenReader(wordFilePath)
    if err != nil {
        fmt.Println("Failed to open zip file: ", err)
        return
    }
    defer r.Close()

    // Iterate through the files in the zip archive
    for _, f := range r.File {
        if strings.HasPrefix(f.Name, "word/embeddings/") && strings.HasSuffix(f.Name, ".xlsx") {
            // Extract and save Excel file
            excelFileName := filepath.Base(f.Name)
            excelFilePath := excelSaveDirPath + "/" + excelFileName
            fmt.Println("Extracting Excel file: ", excelFileName)
            excelFile, err := os.Create(excelFilePath)
            if err != nil {
                fmt.Println("Failed to create Excel file: ", err)
                return
            }
            defer excelFile.Close()
            excelReader, err := f.Open()
            if err != nil {
                fmt.Println("Failed to open Excel file: ", err) 
                return
            }
            defer excelReader.Close()
            _, err = io.Copy(excelFile, excelReader)
            if err != nil {
                fmt.Println("Failed to save Excel file: ", err)
                return
            }
        }
    }
}

以上代码通过使用zip包打开Word文档,并迭代每个zip.Entry(类似于文件)。如果条目的名称以“word/embeddings/”开头且以“.xlsx”结尾,则表示该条目是Excel文件的嵌入对象。然后,提取并保存Excel文件到指定目录。

请注意,上面的实现并未解压整个Word文档,而是只处理了包含Excel文件的zip.Entry。这种方法的好处是避免占用不必要的空间和时间,但它也意味着不能读取Word文档中的其他内容。如需读取整个Word文档,请参考其他go-zip库文档,或使用其他文档读取库。


六、通过 c#和c++实现提取Word文档中的Excel附件并识别文件名保存

在C#和C++中,可以使用Microsoft.Office.Interop.Word库来提取Word文档中的Excel附件并识别文件名保存。以下是C#代码示例:

using Microsoft.Office.Interop.Word;

// ...

string wordFilePath = "path/to/word/file.docx";
string excelSaveDirPath = "path/to/excel/save/dir";

Application wordApplication = new Application();
Document wordDocument = wordApplication.Documents.Open(wordFilePath);

// Iterate over each embedded object and extract Excel files
foreach (InlineShape shape in wordDocument.InlineShapes) {
    if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "Excel.Sheet.12") {
        string embeddedFilePath = Path.Combine(excelSaveDirPath, shape.OLEFormat.IconLabel);
        shape.OLEFormat.Object.SaveAs(embeddedFilePath);
    }
}

// Close resources
wordDocument.Close(false);
wordApplication.Quit(false);

以上代码通过加载Word文档并使用Microsoft.Office.Interop.Word库提取包含Excel附件的OLE对象。针对每个OLE对象检查其类型是否为“Excel.Sheet.12”,如果是,则将Excel文件提取并保存到指定目录中,使用OLE对象的IconLabel属性作为Excel文件名。


以下是C++代码示例:

#include <iostream>
#include <msword.olb>
#include <atlcomcli.h>

void extractExcelFromWord(std::string wordFilePath, std::string excelSaveDirPath) {
    CoInitialize(NULL);

    _ApplicationPtr wordApplication;
    _DocumentPtr wordDocument;
    _InlineShapesPtr inlineShapes;

    // Start Word and open document
    wordApplication.CreateInstance("Word.Application");
    wordApplication->Visible = false;
    wordDocument = wordApplication->Documents->Open(&wordFilePath[0]);

    // Extract Excel files from Word document
    inlineShapes = wordDocument->InlineShapes;
    for (long i = 1; i <= inlineShapes->Count; ++i) {
        InlineShapePtr shape = inlineShapes->Item(i);
        if (shape->OLEFormat != NULL && shape->OLEFormat->ClassType == "Excel.Sheet.12") {
            std::string embeddedFilePath = excelSaveDirPath + "\\" + shape->OLEFormat->IconLabel;
            shape->OLEFormat->Object->SaveAs(&embeddedFilePath[0]);
        }
    }

    // Close resources
    wordDocument->Close(0);
    wordApplication->Quit(0);

    CoUninitialize();
}

int main() {
    std::string wordFilePath = "path\\to\\word\\file.docx";
    std::string excelSaveDirPath = "path\\to\\excel\\save\\dir";
    extractExcelFromWord(wordFilePath, excelSaveDirPath);
    return 0;
}

以上代码通过加载Word文档使用Microsoft.Office.Interop.Word库提取包含Excel附件的OLE对象。For循环来迭代每个InlineShape,如果Shape的类型是Excel文档,则将其保存到指定的文件夹中,使用OLE对象的IconLabel属性作为Excel文件名。

请注意,在C++中使用Microsoft.Office.Interop.Word库需要将Microsoft Word安装到电脑上,并添加对msword.olb库的引用。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈书予

孩子快饿死了 求求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值