Как вставить фрагмент кода в word

Есть программный код на C++, который необходимо вставить в отчет по работе в Word 2013.

Но если напрямую вставлять его — то получается совершенно не читаемая белиберда.

Хочется оформить так, как код выглядит в компиляторе — с номерами строк, правильным форматированием и подсветкой синтаксиса.

Встроенных средств для этого я не нашел. Подскажите, как это можно сделать?


  • Вопрос задан

    более трёх лет назад

  • 106386 просмотров

Встроенных средств для этого я не нашел

Как так? Создаете свой стиль, там настраивайте шрифт, отступы, табуляцию и тд. Вставляете текст и применяете к нему ваш стиль. Подстветка останется, если в стиле не переопределять цвет шрифта.

С номерами строк придется труднее — надо будет настроить свой стиль нумерации, и в созданном выше стиле абзаца указать, чтобы использовать эту нумерацию.

Например, можно добиться вот таких результатов

d3f872c8ac0f86f21245f705525da54b.png

Скачать док: https://www.dropbox.com/s/8fvq11sw5k0tvky/example….

Пригласить эксперта

tohtml.com/ — онлайн-редактор кода с подсветкой синтаксиса для кучи разных языков. Полученное скопипастить в Word.

Из Microsoft Visual Studi, Qt Creator, Eclipse (да вроде почти из всех IDE), код копируется отформатированный, с подсветкой и т.д.

С номерами строк вам наверное не помогу, но вот подсветка отлично копируется из Qt Creator.

Я для этих целей Notepad++ — у него есть ф-ция копированя RTF в буффер
единственное что не будет номеров строк кажется

Я всегда вставляю preformatted текст в таблицу.
Таблица состоит из одной большой ячейки, если вставляется самодостаточный кусок кода или фрагмент лога, и из нескольких — если нужны заголовки или комментарии.
А по поводу подсветки синтаксиса в копируемом коде коллеги выше уже всё сказали.


  • Показать ещё
    Загружается…

15 апр. 2023, в 17:32

500 руб./за проект

15 апр. 2023, в 17:30

7000 руб./за проект

15 апр. 2023, в 17:22

3500 руб./за проект

Минуточку внимания

It can be done without taking snapshots of each segment

What to Know

  • To embed a second document into a Word document: Insert > Object > Create New > Word Document > clear Display as icon > OK.
  • You can also use Paste Special to insert a variety of data into a document, including code.

This article explains issues with using source code in Word for Microsoft 365, Word 2019, Word 2016, Word 2013, Word 2010, and Word 2007 and instructions for embedding a second document in a Word file. It also provides information on pasting other data into a Word document.

The Problem With Using Source Code in Word

Programmers write software programs using languages such as Java, C++, and HTML. Programming languages use different formatting and symbols from regular languages, so pasting a snippet of code into Word from a programming application causes errors such as text reformatting, indentation shifts, link creation, and misspellings.

Given how Microsoft Word structures documents, inserting and working with source code is more difficult than working in a dedicated code editor. However, document embeds create a container that protects source code from being reformatted.

One way to avoid these formatting issues is to paste the source code into a separate document within the main Word document.

Embed a Second Document Into a Word Document

Here’s how to paste source code into a Word document using a second embedded document.

These instructions only work with a single page of code.

  1. Open the target document in Microsoft Word and place the cursor where the source code will appear.

  2. Select Insert.

  3. In the Text group, select Object.

  4. In the Object dialog box, select the Create New tab.

  5. In the Object type list, Select Microsoft Word Document.

    In Word 2007, select OpenDocument Text.

  6. Clear the Display as icon check box.

  7. Select OK.

  8. A new document opens, titled Document in [target document file name]. Save the document in the same folder as the target document.

  9. Copy and paste the source code into the new document. Word automatically ignores the spaces, tabs, and other formatting problems. Spelling errors and grammatical errors are highlighted in the document, but these errors are ignored when the code is inserted in the original document.

  10. Save and close the source code document. The source code appears in the main document.

  11. Resume work on the main document.

Using Different Paste Types in Word

The most up-to-date versions of Word handle code better than they used to. Word for Microsoft 365 supports several forms of pasting, including with and without source formatting. So pasting a block of code from, for example, Microsoft Visual Studio Code will look different based on the paste type. If you select Paste Special, each of the three options yields a different result:

  • Unformatted Text: All code is pasted as unformatted, so you’ll lose indenting, color, typeface, and related contextual clues.
  • HTML Format: From VSC, a paste-as-HTML renders what appears to be a photo of the code, complete with the text editor’s background color. This code block is editable, and you can remove the background color in the Paragraph Fill menu option.
  • Unformatted Unicode Text: Pastes the text as is but strips the text and background colors. Re-format the code as needed.

FAQ

  • How do I see formatting marks and codes in Word?

    To see formatting marks and codes in Word temporarily, go to Home and select the Show/Hide icon to toggle marks on and off. To keep them on permanently, go to File > Options > Display > Show all formatting marks > OK.

  • How do I add links in Word documents?

    To add a link in a Word document, highlight the text you want to hyperlink, right-click it, and select Link. Alternatively, select Insert > Links > Link and enter the URL.

  • How do I convert a Word document to HTML?

    To convert a Word document to HTML, go to File > Save As. Under Save as Type, choose .html. You can also use an editor like Dreamweaver.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Как можно красиво оформить исходный код на языке си для курсовой работы в ворде, которую потом буду печатать?

Kyubey's user avatar

Kyubey

31.5k19 золотых знаков79 серебряных знаков104 бронзовых знака

задан 24 фев 2014 в 19:05

ВладиславМСК's user avatar

ВладиславМСКВладиславМСК

1,51311 золотых знаков37 серебряных знаков59 бронзовых знаков

5

Воспользуйтесь любым сервисом подсветки синтаксиса. Например, первое, что попало в поиске — http://hilite.me/ . Подсвеченный текст можно скопировать и вставить в ворд. Вот ещё один сервис.

А ещё есть плагин для ворда — ADX Toys 2 WD (легко гуглиться).

ответ дан 24 фев 2014 в 19:53

KoVadim's user avatar

KoVadimKoVadim

112k6 золотых знаков91 серебряный знак158 бронзовых знаков

Обычно достаточно вставить текст как есть, выбрать моноширинный шрифт (Courier New или Consolas например) и убрать междустрочный интервал. На подсветку преподам пофиг.

ответ дан 19 апр 2014 в 10:02

insolor's user avatar

insolorinsolor

45.2k15 золотых знаков53 серебряных знака94 бронзовых знака

В большинстве случаев люди, как правило, используют Блокнот для добавления блоков кода и команд, но если у вас уже открыт Microsoft Word, то нет необходимости запускать Блокнот вообще. Из того, что мы можем сказать, Microsoft Word так же хорош, если не лучше, если вы знаете, как вставлять команды и блоки кода. давайте посмотрим, как добавлять блоки кода и команды в Microsoft Word.

Теперь существует несколько способов вставки блоков кода и команд в Word, но их не так много. Все сводится к тому, хотите ли вы, чтобы читатель имел возможность копировать содержимое или просто просматривать его. Как и ожидалось, мы собираемся обсудить, как выполнить каждую задачу. Не беспокойтесь, потому что все будет легко понять.

  1. Скопируйте блок кода или команду
  2. Откройте Microsoft Word
  3. Вставить содержимое как HTML
  4. Вставить код как объект
  5. Используйте Easy Syntax Highlighter

1]Скопируйте блок кода или команду

Где бы вы ни сохранили блок кода или команду, вы должны скопировать соответствующий контент, прежде чем мы сможем отправить его в Microsoft Word.

  • Нажмите CTRL + A, чтобы выделить код.
  • Оттуда нажмите CTRL + C, чтобы скопировать все.
  • Или используйте клавиатуру, чтобы выделить определенный раздел кода.
  • Затем нажмите CTRL + C, чтобы скопировать.

2]Откройте Microsoft Word

Следующим шагом здесь является открытие пустого документа Microsoft Word. Сюда мы будем вставлять недавно скопированный блок кода или команду.

  • Откройте приложение Word с рабочего стола или через раздел «Приложения».
  • В главном меню нажмите «Пустой документ».

Теперь вы должны смотреть на пустой документ, готовый для заполнения содержимым.

3]Вставить содержимое как HTML

Как добавить блоки кода и команды в Microsoft Word

Если вы хотите, чтобы люди скопировали команду или блок кода из вашего документа, мы предлагаем использовать функцию «Специальная вставка как HTML». Это один из самых быстрых способов добавить такое содержимое в документ Word, поскольку он вставляет код без использования другого форматирования документа.

  • Поместите курсор мыши в раздел, где вы хотите, чтобы код появился.
  • Перейдите на вкладку «Главная».
  • После этого вы должны нажать кнопку «Вставить», расположенную на ленте.
  • В раскрывающемся меню выберите «Специальная вставка».
  • Выберите вариант, который гласит: Формат HTML.
  • Нажмите кнопку ОК.
  • Блок кода или команда теперь должны быть видны в формате HTML.
  • Вернитесь на вкладку «Главная», чтобы раскрасить указанный раздел вашего кода, если хотите.

Легко, верно? Мы согласны.

4]Вставьте код как объект

Объект Microsoft Word

Этот вариант для тех, кто хочет поделиться своим кодом или командой с другими, но не давая возможности скопировать. Зрители могут только смотреть, но не могут трогать, что не мешает им делать скриншоты.

  • Найдите вкладку «Вставка» в Microsoft Word.
  • Теперь вы должны нажать на значок объекта.
  • В раскрывающемся меню выберите Объект.
  • Теперь должно появиться новое окно, известное как «Объект».
  • В этом окне выберите OpenDocument Text.
  • Нажмите кнопку ОК.
  • Загрузится новое окно документа.
  • Теперь вы можете вставить скопированный блок кода или команду в этот новый документ.
  • Наконец, закройте документ.

Если все пойдет по плану, код или команда должны появиться в исходном документе Word как объект.

5]Используйте Easy Syntax Highlighter

Выделить выделение Microsoft Word

Если вы хотите выделить блоки кода и команды, мы предлагаем загрузить надстройку Microsoft Word, известную как Easy Syntax Highlighter. Посетить официальная страница чтобы получить его в вашей системе прямо сейчас.

  • Теперь, когда надстройка запущена и работает, вставьте блок кода или команду.
  • Выберите команду или код.
  • Оттуда перейдите на вкладку Easy Syntax Highlighter.
  • Чтобы применить форматирование по умолчанию, нажмите «Выделить выделение».
  • Ваш фрагмент будет выделен и отформатирован.

Читайте: Как деформировать и конвертировать несколько слов в одну фигуру в Illustrator

Как вставить HTML-код в документ Word?

Вставка HTML-кодов в документ Word — простая задача, если вы знаете, что делаете.

  • Все, что вам нужно сделать, это открыть пустой документ Word.
  • Перешел на вкладку «Вставка».
  • Перейдите в раздел «Текст».
  • Нажмите на значок объекта.
  • Выберите Текст из файла.
  • Воспользуйтесь селектором типа файла в поле «Вставить файл».
  • Выберите параметр «Все веб-страницы».
  • Теперь должно появиться окно «Преобразовать файл».
  • Выберите другую кодировку.
  • Наконец, нажмите кнопку ОК.

Вы можете писать код в Microsoft Word?

Вы можете писать в Microsoft Word все, что хотите, потому что, в конце концов, это инструмент для обработки текстов. Тем не менее такие инструменты, как «Блокнот», всегда будут лучшими для написания кода благодаря их простоте и специализированным функциям.

I have to write some documents that will include source code examples. Some of the examples will be written from the IDE, and others would be written in place. My examples are primarily in Java.

As someone who is used to LaTeX, doing this in Word is extremely painful. However, I am bound to Word for this. The only options I have seen are:

  1. Write or copy into the document,
    then use a fixed type font, arrange
    formatting and hope that Word didn’t
    uppercase stuff for you. Needless to
    say, this looks like crap.
  2. Copy and paste screenshots of source
    code from the IDE. At least I keep
    colors. However, if I change my font
    size, I’m screwed. I’m also screwed
    across page boundaries. And let’s
    admit it, Word is not great at
    managing multiple images on a
    document.
  3. Write HTML (not really an option
    here)

Is there some better (and ideally portable) way to do this? Is there at least some sort of verbatim style similar to the LaTeX environment? Is there at least some pretty printer that I could copy-and-paste as RTF?

Todd Main's user avatar

Todd Main

28.9k11 gold badges82 silver badges146 bronze badges

asked Jul 15, 2010 at 2:35

Uri's user avatar

9

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box — it may be too small …
    04word
  5. … so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption …
    06word
  7. In the Caption menu, if you don’t have one already, click New Label, and set the new label to «Code», click OK …
    07word
  8. … then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

answered May 14, 2014 at 8:44

sdaau's user avatar

sdaausdaau

36.5k44 gold badges195 silver badges273 bronze badges

7

I recently came across this post and found some useful hints. However, I ended up using an entirely different approach which suited my needs. I am sharing the approach and my reasoning of why I chose this approach. The post is longer than I would have liked, but I believe screenshots are always helpful. Hopefully, the answer would be useful to someone.

My requirements were the following:

  1. Add code snippets to a word document, with syntax highlighting for easier visibility and differentiation of code and other text.
  2. Code snippet shall be inline with other text.
  3. Code snippet shall break across pages smoothly without any extra effort.
  4. Code snippet shall have a nice border.
  5. Code snippet shall have spell-check disabled.

My Approach is as listed below:

  1. Use external tool to achieve syntax highlighting requirement 1 above.
    One could use notepad plus plus as described above. However, I use the tool present here — https://syntax-highlighter.k26.ch/. This gives me the option to use line number, as well as very nice syntax highlighting (Please use Google Chrome for this step, because syntax highlight is not copied when using Mozilla Firefox, as also pointed out by couple of user comments). Steps to achieve syntax highlighting are listed below:
  • Open the website provided above in chrome and Copy the code snippet in the text area. I will be using a sample XML to demonstrate this (XML sample from here — http://www.service-architecture.com/articles/object-oriented-databases/xml_file_for_complex_data.html).

  • Select the language from drop down menu.

  • Click «Show Highlighted» button. It will open a new tab, with syntax-highlighted code snippet, in this case the XML sample we chose. See image below for example.
    Image shows a sample xml being pasted in the textarea, language selected as XML and the button.

  • To Turn off the line numbers, inspect the page in chrome. Then, under styles, deselect the «margin» property in «.dp-highlighter ol», as shown in the image below. If you want to keep the line numbers, go to next step.

  • Select the syntax-highlighted code and click copy. Now your code is ready to be pasted into Microsoft word.
    Result of syntax-highlighted XML
    Thanks to this blog for providing this information — http://idratherbewriting.com/2013/04/04/adding-syntax-highlighting-to-code-examples-online-and-in-microsoft-word/.
    2. To achieve requirements 2, 3 and 4 above, use table in Microsoft word, to insert the code snippet. Steps are listed below:

  • Insert a table with single column.

  • Paste the copied text from step 1. in the table column. I have kept the line numbers to show how well this works with Microsoft word.

  • Apply border, as you like. I have used size 1pt. Resulting Microsoft word snippet will appear as shown in screenshot below. Note how nicely it breaks across the page — NO extra effort needed to manage this, which you would face if inserting «OpenDocument Text» object or if using «Simple TextBox».
    Syntax-highlighted code snippet pasted in Microsoft Word Table

    1. To achieve requirement 5, follow the steps below:
  • Select the entire table or the text.

  • Go to Review tab. Under Language, choose «Proofing Language». A new pop-up will be presented.

  • Select «Do not check spelling or grammar». Then, click OK.
    Disable spell-check

  • Resulting text has spell-check disabled. Final result is shown in the image below and meets all the requirements.
    Final Result - meets all the 5 requirements.

Please provide if you have any feedback or improvements or run into any issues with the approach.

Nicicalu's user avatar

Nicicalu

7197 silver badges16 bronze badges

answered Jun 6, 2016 at 19:12

abhishek's user avatar

abhishekabhishek

6316 silver badges14 bronze badges

12

You need to define a style in your Word document and use that for source code. I usually have a style called «Code» which has a monospaced font in a small point size, fixed size tabs, single line spacing, no before/after paragraph spacing, etc. You only need to define this style once and then reuse it. You paste in your source code and apply the «Code» style to it.

Note that some editors (e.g. Xcode on the Mac) add RTF as well as text to the clipboard when copying/pasting between applications — Word recognises RTF and helpfully retains the formatting, syntax colouring, etc.

Source code in Xcode:

enter image description here

Copied and pasted to Word:

enter image description here

(Note: it’s a good idea to disable spell-checking in your «Code» style in Word.)

answered Jul 15, 2010 at 5:43

Paul R's user avatar

Paul RPaul R

207k35 gold badges384 silver badges552 bronze badges

6

It kind of depends on the IDE. Both Visual Studio and Eclipse, for example, will allow you to copy as RTF and paste into Word, keeping all your formatting.

Notepad++ has a plugin called «NppExport» (comes pre-installed) that allows you to copy to RTF, though I don’t care much for Notepad++’s syntax highlighting (it’d definitely be passable though). What it does do is support dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

answered Jul 15, 2010 at 2:45

Cᴏʀʏ's user avatar

CᴏʀʏCᴏʀʏ

104k20 gold badges166 silver badges193 bronze badges

1

Use this — http://hilite.me/

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.

How:
Just copy the source code to the left pane, select the language and the color scheme, and click «Highlight!». The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.

For Microsoft Word document: Copy the the content from the Preview section and paste to your Microsoft Word document.

3 sections : Source Code , HTML and Preview

answered Oct 11, 2019 at 3:02

Saghir Hussain's user avatar

These answers look outdated and quite tedious compared to the web add-in solution; which is available for products since Office 2013.

I’m using Easy Code Formatter, which allows you to codify the text in-place. It also gives you line-numbering options, highlighting, different styles and the styles are open sourced here: https://github.com/armhil/easy-code-formatter-styles so you could extend the styling yourself. To install — open Microsoft Word, go to Insert Tab / click «Get Add-ins» and search for «Easy Code Formatter»

enter image description here
enter image description here
enter image description here

answered Jun 19, 2020 at 11:30

Mavi Domates's user avatar

Mavi DomatesMavi Domates

4,2372 gold badges23 silver badges43 bronze badges

1

This is related to this answer: https://stackoverflow.com/a/2653406/931265
Creating an object solved all of my problems.

Insert > Object > Opendocument Text

This will open a document window, paste your text, format it how you want, and close it.

The result is a figure. Right click the object, and select ‘add a caption’.

You can now make cross references, create a table of figures.

Community's user avatar

answered Mar 14, 2013 at 20:12

rickfoosusa's user avatar

rickfoosusarickfoosusa

1,03119 silver badges26 bronze badges

1

If you are still looking for an simple way to add code snippets.

you can easily go to [Insert] > [Object] > [Opendocument Text] > paste your code > Save and Close.

You could also put this into a macro and add it to your easy access bar.

notes:

  • This will only take up to one page of code.
  • Your Code will not be autocorrected.
  • You can only interact with it by double-clicking it.

answered Jun 28, 2018 at 13:43

Meatyflesh's user avatar

1

There is an easy way if you want simple code formatting.

  1. Open word> Insert tab> click on «Get Add-ins»
  2. search for «Content mixer»
    3.click on «Add»

Then content mixer add will open automatically and you can copy paste your code in there and click on «Insert» to insert it in word doc.

answered Sep 6, 2019 at 17:59

Hitesh Bisht's user avatar

Hitesh BishtHitesh Bisht

4681 gold badge6 silver badges11 bronze badges

You can use Open Xml Sdk for this. If you have the code in html with color and formatting. You can use altchunks to add it to the word documents.
Refer this post Add HTML String to OpenXML (*.docx) Document
Hope this helps!

Community's user avatar

answered Jan 9, 2014 at 8:40

Mohamed Alikhan's user avatar

Community's user avatar

answered Aug 2, 2014 at 8:05

USer22999299's user avatar

USer22999299USer22999299

5,1249 gold badges45 silver badges74 bronze badges

In Word, it is possible to paste code that uses color to differentiate comments from code using «Paste Keep Source Formatting.» However, if you use the pasted code to create a new style, Word automatically strips the color coded text and changes them to be black (or whatever the auto default color is). Since applying a style is the best way to ensure compliance with document format requirements, Word is not very useful for documenting software programs. Unfortunately, I don’t recall Open Office being any better.
The best work-around is to use the default simple text box.

answered Jul 24, 2018 at 15:08

user10128757's user avatar

I have tried all your methods, but they didn’t work for me, in fact I have created an easier method using MS Word Tables.

Pros:

  1. More beautiful
  2. Easier to manage & more consistent
  3. Are less prone to problems
  4. No need for external plugins or MS Word micro coding.
  5. Easier to handle by simple users (such as myself).

Cons:
It will not maintain code colouring although someone could improve my trick.

Steps:

  1. Insert a 3×3 table, in my case I always make the total width of the table equals the free page’s width (3 rows minimum to test the tables style).

  2. Use invisible borders («No Borders» option), and activate «View Gridlines» option. it should have this aspect.
    Be ware that those lines are for you to see the table’s grid, and the will not be printed.

enter image description here

  1. Make the adjustments to cells’ spacing and columns’ width to get the aspect you like. (You will have to get in «Table Properties» for fine tuning).
    enter image description here

  2. Create a «Paragraph Style» with the name of «Code» just for your code snippets (check https://stackoverflow.com/a/25092977/8533804 to get the idea, you don’t have to follow all of it)

  3. Create another «Paragraph Style» with the name of «Code_numberline» that will be based upon the previous created style.
    enter image description here

  4. In the newly created «Code_numberline» add the numbering style that you like (this will automate line numbering).
    enter image description here

  5. Apply «Code_numberline» to the first column, and «Code» to the 3 column.
    enter image description here

  6. Add a fill in the middle column.
    enter image description here

  7. Save that table style and enjoy!

answered Nov 5, 2018 at 12:29

Nader Belal's user avatar

Nader BelalNader Belal

1573 silver badges10 bronze badges

5

So I’ve found the majority of answers on this question to either be only semi-functional or broken entirely (eg the website used is down). This solution is entirely self-contained in Word, works across multiple pages, and keeps your syntax highlighting.

Here’s the steps:

  1. Temporarily set your IDE’s theme to a light one, so that the text will fit in with the rest of your document.
  2. Copy the required code (HTML colourising info will be copied with it).
  3. In Word, hit Ctrl+Alt+V and choose HTML Format to paste the coloured text.
  4. Select all your text and then expand the styles gallery on the home tab of the ribbon.
  5. Choose «Create a style». Use a name such as «Code»
  6. Right click your new style in the gallery and choose «Modify».
  7. Under the formatting section, change the font to Consolas or your choice of monospace font. Also set the line spacing to Condensed (this option is next to the text alignment options).
  8. Under the format button in the bottom left, choose «Language», then enable the «Don’t check spelling or grammar» option.
  9. If you want this style to be available in future documents, change to the «New documents based on this template» radio button.

Optional: for line numbers…

  1. Back in the Modify Style dialogue, choose the format button again and choose «Numbering».
  2. Choose the «Define new number format» option.
  3. Remove the dot after the number ‘1’ in the number format box.
  4. Choose «Right» as the number alignment.
  5. Hit ok, then select your new number alignment option. Finally, hit ok on the Modify Style dialog.

Finally, select your code, and set it to be the Code style, which should apply all the required formatting.

answered Jul 12, 2021 at 17:55

Miguel Guthridge's user avatar

Как вставить исходный код в документ Word

Это может быть сделано без снимков каждого сегмента

Если вы программист или разработчик программного обеспечения, вам может быть сложно использовать Microsoft Word для работы с исходным кодом. Существует способ вставить исходный код в документ Word, не делая снимки каждого сегмента кода.

Инструкции в этой статье относятся к Word 2019, 2016, 2013, 2010, 2007; и Word для Office 365.

Проблема с использованием исходного кода в Word

Программисты пишут программы, используя такие языки, как Java, C ++ и HTML. Они используют различное форматирование и символы из обычных языков, поэтому вставка фрагмента кода в Word из приложения программирования приводит к ошибкам, таким как переформатирование текста, сдвиг отступов, создание ссылок и орфографические ошибки.

Один из способов избежать этих проблем форматирования – вставить исходный код в отдельный документ, который отображается в вашем основном документе Word.

Вставить второй документ в документ Word

Вот как вставить исходный код в документ Word, используя второй встроенный документ.

Эти инструкции работают только с одной страницей кода.

Откройте целевой документ в Microsoft Word и поместите курсор туда, где появится исходный код.

Перейдите на Вставить .

В группе Текст выберите Объект .

В диалоговом окне Объект выберите вкладку Создать новый .

В списке Тип объекта выберите Документ Microsoft Word . В Word 2007 выберите Текст OpenDocument .

Снимите флажок Показать как значок .

Выберите ОК .

Откроется новый документ под названием Документ в [ имя файла целевого документа ] . Сохраните документ в той же папке, что и целевой документ.

Скопируйте и вставьте исходный код в новый документ. Word автоматически игнорирует все пробелы, вкладки и другие вопросы форматирования. Ошибки орфографии и грамматические ошибки выделены в документе, но когда код вставлен в исходный документ, эти ошибки игнорируются.

Сохраните и закройте документ с исходным кодом. Исходный код появляется в основном документе.

Возобновить работу над основным документом.

Как добавить отформатированный код в документ Microsoft Word?

Мне нужно написать документ в MS-Word 2007, который содержит множество примеров кода VB.NET и C #.

Каков наилучший способ заставить код выглядеть разумно в документе?

Какие стили и т.д. используют люди?

(У меня нет времени на ручное редактирование / форматирование кода, и я был бы очень рад, если бы он выглядел так же, как в студии разработчиков)

В других работах, которые делают люди, которые пишут книги по программированию, для этого должно быть хорошее автоматизированное решение .

Я бы хотел использовать таблицы стилей слов для управления тем, как выглядит код, но не хочу «выбирать» каждое ключевое слово и т. Д., Чтобы установить его стиль.

Вы можете использовать службы выделения исходного текста и скопировать / вставить в документ Word. Я думаю, что это будет самый быстрый способ ( обн. Также будет работать простая копировальная паста от VS).

Второй способ — создать стиль для блока кода, сохранить его, а затем применить ко всем блокам кода.

Word изначально не поддерживает подсветку синтаксиса или другое форматирование кода. Поэтому лучше всего создавать подсветку и т. Д. В другой программе (visual studio, eclipse, notepad ++ или на этом веб-сайте, который может работать на 14 языках и не требует установки).

Однако при вставке текста выполнение этого непосредственно в самом текстовом документе может привести к таким головным болям, как орфография и грамматические подчеркивания.

Чтобы это исправить, вместо прямого копирования и вставки используйте Вставка -> Объект -> Текст OpenDocument . Это откроет новый документ. Вставьте текст сюда и закройте окно. Ваш код теперь будет отображаться как объект с полным форматированием, показанным в предыдущем окне, но без проверки орфографии или проверки грамматики.

Хотя можно отформатировать код с помощью стилей, для этого нет встроенных стилей, и это не совсем то, для чего предназначены стили. Если вы хотите использовать стили для форматирования кода, просто используйте этот стиль во всех создаваемых вами объектах.

Обновление: если вы хотите сделать это со стилями кода, вот несколько идей.

  • Используйте стиль абзаца с моноширинным шрифтом
  • Светлый фон (серый работает хорошо)
  • Орфография выключена
  • Убедитесь, что межстрочный интервал соответствует желаемому

Если вы хотите добавить немного больше сложности, вы можете наложить стили символов поверх стиля абзаца, чтобы создать нечто похожее на предварительный просмотр кода в stackoverflow с другим форматированием и / или цветом для имен классов, имен экземпляров и т. Д.

Настройка стиля, подобного этому, требует работы, но вы можете получить более настраиваемый результат по сравнению с тем, что вы можете получить, используя подсветку синтаксиса в notepad ++ или Visual Studio.

В качестве ускорения при форматировании кода со стилем, это может помочь сначала выполнить подсветку синтаксиса в одной из этих программ, а затем использовать утилиту поиска Word для поиска текста, который соответствует цвету или другому стилю шрифта, так что вам не нужно вручную определить, что такое имя класса, например, в коде вручную (оно находится под форматом more-> в приглашении поиска).

Вставка кодов символов ASCII или Юникода в Word

Вставка символа с помощью клавиатуры с кодами символов ASCII или Юникода

Символы и специальные знаки вставляются с помощью кодов ASCII или Юникода. Вы можете укассировать код при подытовом коде для знака.

Перейдите на вкладку > символ > другие символы.

Найдите нужный символ.

Совет: Шрифт Segoe UI Symbol содержит очень большой набор символов Юникода, которые можно выбрать.

В правой нижней части вы увидите код знака и от:. Код знака используется для вставки этого символа с клавиатуры. Поле «От»: указывает, является ли это кодом Юникода или символом ASCII.

Юникод

ASCII

Вставка символов Юникод

Введите код символа там, куда необходимо вставить знак в кодировке Юникод.

Нажмите клавиши ALT + X, чтобы преобразовать код в символ.

Если символ Юникода нужно поместить сразу после другого, выделите код, прежде чем нажимать ALT+X.

Совет: Если вы не получили символ, который вы ожидали, убедитесь в том, что выбран правильный шрифт.

Вставка символов ASCII

На цифровой клавиатуре с помощью клавиши Num Lock введите номера ASCII, а не номера в верхней части клавиатуры.

Все коды символов ASCII имеют четыре цифры. Если код символа меньше четырех цифр, добавьте нули в начале, чтобы получить 4 цифры.

На вкладке Главная в группе Шрифт измените шрифт на Wingdings (или другой набор шрифтов).

Нажмите клавишу ALT и, удерживая ее, введите код символа с помощью цифровой клавиатуры.

После вставки символа измените шрифт на предыдущий.

Понравилась статья? Поделить с друзьями:
  • Как вставить фрагмент в excel
  • Как вставить числовые данные в excel
  • Как вставить фрагмент pdf в word
  • Как вставить число с другого листа excel
  • Как вставить фотографию в ячейку excel