Вывод текста построчно в файл .docx - C#

Узнай цену своей работы

Формулировка задачи:

Доброго времени суток! Есть следующий код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace KP_DEMO
{
    public partial class Form1 : Form
    {
        string put;
        public Word.Application wordapp;
        public Word.Document worddocument;
        private Word.Paragraphs wordparagraphs;
        private Word.Paragraph wordpararaph;
        public bool ind=false;
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {   
           
            wordapp = new Word.Application();
            openFileDialog1.ShowDialog();
            put = openFileDialog1.FileName;
            wordapp.Visible = false;
            Object filename = put;
            Object confirmConversions = true;
            Object readOnly = false;
            Object addToRecentFiles = true;
            Object passwordDocument = Type.Missing;
            Object passwordTemplate = Type.Missing;
            Object revert = false;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format = Type.Missing;
            Object encoding = Type.Missing; ;
            Object oVisible = Type.Missing;
            Object openConflictDocument = Type.Missing;
            Object openAndRepair = Type.Missing;
            Object documentDirection = Type.Missing;
            Object noEncodingDialog = false;
            Object xmlTransform = Type.Missing;
           worddocument=wordapp.Documents.Open(ref filename,ref confirmConversions, ref readOnly, ref addToRecentFiles,
           ref passwordDocument, ref passwordTemplate, ref revert,
           ref writePasswordDocument, ref writePasswordTemplate,
           ref format, ref encoding, ref oVisible,
           ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform);
           wordparagraphs = worddocument.Paragraphs;
           int k = 1;
           Object oMissing = System.Reflection.Missing.Value;
           while(k<=10)
           {
               wordpararaph = (Word.Paragraph)wordparagraphs[k];
               wordpararaph.Range.Text = "Проба";
               worddocument.Paragraphs.Add(Type.Missing);
               k++;
           }
          // textBox1.Text = wordpararaph.Range.Text;
           wordapp.Visible = true;
            ind=true;
        }
 
        private void выходToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if(ind==true)
{
            wordapp.Quit(Word.WdSaveOptions.wdSaveChanges);
}
            Application.Exit();
            
        }
    }
}
Как видно из кода, из диалога получаем путь, создаем объект Word.Application, заполняем его текстом "Проба", по 10 строкам. Однако при повторном выводе в этот же файл строки не заменяют друг-друга, а заполнение происходит добавлением слова "проба" к первым 5 строкам. Как сделать именно построчный вывод(желательно с заменой текста, который находится в строке, на текст выводимый)? Заранее спасибо!

Решение задачи: «Вывод текста построчно в файл .docx»

textual
Листинг программы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
 
namespace DEMO_XML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.ShowDialog();
            string put;
            put = op.FileName;
            string vstavka = "ras_ras";
            WordprocessingDocument vvoddoc = WordprocessingDocument.Open(put, true);
            Body body = vvoddoc.MainDocumentPart.Document.Body;
 
            // Add new text.
            //Paragraph para = body.AppendChild(new Paragraph());
            //Run run = para.AppendChild(new Run());
            //run.AppendChild(new Text(vstavka));
            //Paragraph para2 = body.AppendChild(new Paragraph());
            //Run run2 = para2.AppendChild(new Run());
            //run2.AppendChild(new Text(vstavka)); 
            IEnumerable<Paragraph> paragraphs = vvoddoc.MainDocumentPart.Document.Body.Descendants<Paragraph>();
            int cnt = 1;
            richTextBox1.Lines[0] = Convert.ToString(paragraphs.Count());
            //foreach (Paragraph p in paragraphs)
            /*{
                int sch=1;
                richTextBox1.Lines[sch]= p.InnerText+ "\n";
                sch++;
            }*/
            // Close the handle explicitly.
            //vvoddoc.Close();
        }
    }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.9 из 5
Похожие ответы