Python doc to docx linux

how to create docx files with python

I am trying to take my data and put it in tables in either microsoft words or libreoffice writer. I need to be able to change the background of cells within the table and I need to be able to change the page property to ‘landscape’. I have been looking for a library with simple code ( I am a beginner in coding ) but I did not find one for what I need to do. Have you heard of anything for me ? If there are example on how to use it that would make it easier for me to learn it.

2 Answers 2

It’s pretty simple to use, i haven’t tested this, but it should work:

from docx import Document document = Document() r = 2 # Number of rows you want c = 2 # Number of collumns you want table = document.add_table(rows=r, cols=c) table.style = 'LightShading-Accent1' # set your style, look at the help documentation for more help for y in range(r): for x in range(c): cell.text = 'text goes here' document.save('demo.docx') # Save document 

It don’t think you can set the page orientation property with this library, but what you could do is create a blank word document that is in landscape yourself, store it in the working directory and make a copy of it every time you generate this document.

python-docx can indeed set the page orientation. It’s in the section properties and you set it for each section (many documents only need to be one section). You just need to set the «orientation» property for the section object to WD_ORIENT.PORTRAIT or WD_ORIENT.LANDSCAPE to get the orientation you want. Link to details: python-docx.readthedocs.org/en/latest/api/section.html#id1

Источник

doc2docx 0.2.4

Convert doc to docx on Windows or macOS directly using Microsoft Word (must be installed).

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Требует: Python >=3.9,

Сопровождающие

Классификаторы

Описание проекта

doc2docx

Convert doc to docx on Windows or macOS directly using Microsoft Word (must be installed).

On Windows, this is implemented via win32com while on macOS this is implemented via JXA (Javascript for Automation, aka AppleScript in JS).

Install

brew install cosmojg/tap/doc2docx 

CLI

usage: doc2docx [-h] [--keep-active] [--version] input [output] Example Usage: Convert single doc file in-place from myfile.doc to myfile.docx: doc2docx myfile.doc Batch convert doc folder in-place. Output docx files will go in the same folder: doc2docx myfolder/ Convert single doc file with explicit output filepath: doc2docx input.doc output.docx Convert single doc file and output to a different explicit folder: doc2docx input.doc output_dir/ Batch convert doc folder. Output docx files will go to a different explicit folder: doc2docx input_dir/ output_dir/ positional arguments: input input file or folder. batch converts entire folder or convert single file output output file or folder optional arguments: -h, --help show this help message and exit --keep-active prevent closing word after conversion --version display version and exit 

Library

See CLI docs above (or in doc2docx --help ) for all the different invocations. It is the same for the CLI and python library.

Jupyter Notebook

If you are using this in the context of jupyter notebook, you will need ipywidgets for the tqdm progress bar to render properly.

pip install ipywidgets jupyter nbextension enable --py widgetsnbextension 

Acknowledgements

Many thanks to @AlJohri for the excellent docx2pdf upon which this is based!

Читайте также:  Linux history all sessions

Источник

multiple .doc to .docx file conversion using python

Here is a solution that worked for me. The other solutions proposed did not work on my Windows 10 machine using Python 3.

from glob import glob import re import os import win32com.client as win32 from win32com.client import constants # Create list of paths to .doc files paths = glob('C:\\path\\to\\doc\\files\\**\\*.doc', recursive=True) def save_as_docx(path): # Opening MS Word word = win32.gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(path) doc.Activate () # Rename path with .docx new_file_abs = os.path.abspath(path) new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs) # Save and Close word.ActiveDocument.SaveAs( new_file_abs, FileFormat=constants.wdFormatXMLDocument ) doc.Close(False) for path in paths: save_as_docx(path) 

I am getting this error —> com_error: (-2147352567, ‘Exception occurred.’, (0, ‘Microsoft Word’, «Sorry, we couldn’t find your file. Was it moved, renamed, or deleted?\r (C:\\//Users/shreyajain/Documents/Docum. )», ‘wdmain11.chm’, 24654, -2146823114), None) Any suggestion?

@Shreyansjain Based on the error message, I’m guessing you typed in the file path incorrectly. Although, it’s difficult to tell without seeing your code.

1) This also allows you to convert PDF files into DOCX, allowing you to read the content of PDF documents. 2) I would suggest to add a TRY at the start of the program, to check that MS-Word is installed : MSWord_OK = True try: word = win32.gencache.EnsureDispatch(‘Word.Application’)

I prefer to use the glob module for tasks like that. Put this in a file doc2docx.py . To make it executable, set chmod +x . And optionally put that file in your $PATH as well, to make it available «everywhere».

#!/usr/bin/env python import glob import subprocess for doc in glob.iglob("*.doc"): subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc]) 

Though ideally you’d leave the expansion to the shell itself, and call doc2docx.py with the files as arguments, like doc2docx.py *.doc :

#!/usr/bin/env python import subprocess import sys if len(sys.argv) < 2: sys.stderr.write("SYNOPSIS: %s file1 [file2] . \n"%sys.argv[0]) for doc in sys.argv[1:]: subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc]) 

As requested by @pyd, to output to a target directory myoutputdir use:

#!/usr/bin/env python import subprocess import sys if len(sys.argv) < 2: sys.stderr.write("SYNOPSIS: %s file1 [file2] . \n"%sys.argv[0]) for doc in sys.argv[1:]: subprocess.call(['soffice', '--headless', '--convert-to', 'docx', '--outdir', 'myoutputdir', doc]) 

From my tests this only fails when the working/target directory in question is the root of the filesystem, e.g. directly C:\ or D:\ . Any other folder works fine. Looks like a bug in soffice . You can specify the output directory by using the option --outdir .

Читайте также:  Linux mint нет разрешения экрана 1920 1080

If you don't like to rely on sub-process calls, here is the version with COM client. It is useful if you are targeting windows users without LibreOffice installed.

#!/usr/bin/env python import glob import win32com.client word = win32com.client.Dispatch("Word.Application") word.visible = 0 for i, doc in enumerate(glob.iglob("*.doc")): in_file = os.path.abspath(doc) wb = word.Documents.Open(in_file) out_file = os.path.abspath("out<>.docx".format(i)) wb.SaveAs2(out_file, FileFormat=16) # file format for docx wb.Close() word.Quit() 

@longbowking There is no swiss knife library to take care of this when I looked last year. One possible method is to detect OS with sys.platform and try Jan Christoph Terasa's approach for Linux, my approach for Windows. Not sure what works for Mac.

Just tried unoconv with this docker image, doc -> docx, but the resulting docx was damaged (files contained comments that I needed to preserve).

import re import os import sys import win32com.client as win32 from win32com.client import constants # Get path from command line argument ABS_PATH = sys.argv[1] def save_as_docx(path): # Opening MS Word word = win32.gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(path) doc.Activate () # Rename path with .docx new_file_abs = os.path.abspath(path) new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs) # Save and Close word.ActiveDocument.SaveAs(new_file_abs, FileFormat=constants.wdFormatXMLDocument) doc.Close(False) def main(): source = ABS_PATH for root, dirs, filenames in os.walk(source): for f in filenames: filename, file_extension = os.path.splitext(f) if file_extension.lower() == ".doc": file_conv = os.path.join(root, f) save_as_docx(file_conv) print("%s ==> %sx" %(file_conv,f)) if __name__ == "__main__": main() 

Источник

Заметка Конвертируем файлы doc в docx с помощью Python

В статье «Конвертация файлов Word в PDF с помощью Python» я описал пример автоматизации, когда множество файлов Word, с помощью скрипта на Python, можно конвертировать в PDF. Но, я так же упоминал, что модуль, который используется для конвертации, не работает со старыми форматами файлов, а именно - с doc. Поэтому, для того, чтобы можно было их конвертировать в pdf, сначала нужно сохранить их в docx. Вроде бы логично, но не делать же это все вручную. Ведь файлов может быть достаточно много, а лень, она такая)

Читайте также:  Аутентификация linux active directory

000.png

Оговорюсь, что сам скрипт не мой. Я его нашел на необъятных просторах stackoverflow.com и немного над ним поиздевался.

Для начала, операционная система Windows, а также установленный Microsoft Word. Но, думаю, что это не проблема. Ну, и установить модуль glob:

screenshot2.png

Вот, что в итоге у меня получилось:

from glob import glob import re import os import win32com.client as win32 from win32com.client import constants def save_as_docx(path): # Открываем Word try: word = win32.gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(path) doc.Activate() # Меняем расширение на .docx и добавляем в путь папку # для складывания конвертированных файлов new_file_abs = str(os.path.abspath(path)).split("\\") new_dir_abs = f"\\" new_file_abs = f"\\\\doc_convert\\" new_file_abs = os.path.abspath(new_file_abs) if not os.path.isdir(f'\\doc_convert'): os.mkdir(f'\\doc_convert') new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs) print(new_file_abs) # Сохраняем и закрываем word.ActiveDocument.SaveAs(new_file_abs, FileFormat=constants.wdFormatXMLDocument) doc.Close(False) except: return str(path).split("\\")[-1] def path_doc(paths): dict_error_file = [] for path in paths: err = save_as_docx(path) if err != None: dict_error_file.append(err) if len(dict_error_file) >= 1: print(f'\nНе конвертированные файлы (ошибка открытия - файл поврежден):\n') def main(): dirs = input(f'Введите путь к папке с файлами\n(пример: C:\\temp) >>> ') paths = glob(f'\\*.doc', recursive=True) path_doc(paths) if __name__ == "__main__": main()

А теперь, как он работает. Для начала пользователь вводит путь до папки, в которой лежат файлы формата doc. Модуль globs рекурсивно обходит все папки и подпапки на наличие в них файлов нужного формата и возвращает список. Далее, этот список передается в функцию def path_doc(paths), которая в цикле передает путь к файлу doc из списка в функцию конвертации. Иногда попадаются такие файлы, которые Word открыть для редактирования не может. А следовательно, они доступны для открытия только в безопасном режиме. Логично, что такой файл не может быть и сохранен. Поэтому функция конвертации, при ошибке открытия файла, возвращает его имя и оно добавляется в список, чтобы потом вывести сообщение о необработанных файлах.

Ну, а функция конвертации открывает документ, путь к которому был передан с помощью MS Word. Теперь нам нужно создать в папке с документами для конвертации папку, в которую будут складываться уже сконвертированные документы. Поэтому производятся манипуляции по разборке и сборке абсолютного пути к файлу. Затем создается папка для конвертируемых документов. Ну, а после, файлу с помощью функции re присваивается новое расширение, с путем для сохранения.

Далее файл сохраняется и, так как он был открыт, закрывается.

Таким образом, конвертация не занимает много времени. По крайней мере, это намного быстрее, чем вручную.

Надеюсь, что данный скрипт кому-то будет полезен. Спасибо за внимание

Источник

Оцените статью
Adblock
detector