Convert a word processing document from the DOCM to the DOCX file format

The ConvertDOCMtoDOCX sample method can be used to convert a Word 2010 or Word 2013 document that contains VBA code (and has a .docm extension) to a standard document (with a .docx extension). Use this method to remove the macros and the vbaProject part that contains them from a document stored in .docm file format.

OpenXML Words

The sample code modifies the document that you specify, verifying that the document contains a vbaProject part, and deleting the part. After the code deletes the part, it changes the document type internally and renames the document so that it uses the .docx extension.

        string fileName= "DOCMtoDOCX.docm";
        public static void ConvertDOCMtoDOCX(string fileName)
        {
            bool fileChanged = false;

            using (WordprocessingDocument document =
                WordprocessingDocument.Open(fileName, true))
            {
                // Access the main document part.
                var docPart = document.MainDocumentPart;

                // Look for the vbaProject part. If it is there, delete it.
                var vbaPart = docPart.VbaProjectPart;
                if (vbaPart != null)
                {
                    // Delete the vbaProject part and then save the document.
                    docPart.DeletePart(vbaPart);
                    docPart.Document.Save();

                    // Change the document type to
                    // not macro-enabled.
                    document.ChangeDocumentType(
                        WordprocessingDocumentType.Document);

                    // Track that the document has been changed.
                    fileChanged = true;
                }
            }

            // If anything goes wrong in this file handling,
            // the code will raise an exception back to the caller.
            if (fileChanged)
            {
                // Create the new .docx filename.
                var newFileName = Path.ChangeExtension(fileName, ".docx");

                // If it already exists, it will be deleted!
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }

                // Rename the file.
                File.Move(fileName, newFileName);
            }
        }

Aspose.Words

We can use Document constructor of Aspose.Words API to load .doc or .docm files and use Document.Save method to save to .docx.

            Document doc = new Document(DOCMtoDOCX.docm);
            var newFileName = Path.ChangeExtension(fileName, ".docx");
            doc.Save(DOCMtoDOCX, SaveFormat.Docx);

Download

Last edited May 26, 2015 at 4:21 AM by asposemarketplace, version 2