Здравствуйте, помогите пожалуйста, как реализовать сохранение текста из Textblock в файл .docx/doc???
http://www.c-sharpcorner.com/UploadFile/muralidharan.d/how-to-create-word-document-using-C-Sharp/
private void button1_Click(object sender, EventArgs e)
{
CreateDocument();
}
//Create document method
private void CreateDocument()
{
try
{
//Create an instance for word app
Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
//Set animation status for word application
winword.ShowAnimation = false;
//Set status for word application is to be visible or not.
winword.Visible = false;
//Create a missing variable for missing value
object missing = System.Reflection.Missing.Value;
//Create a new document
Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
//Add header into the document
foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
{
//Get the header range and add the header details.
Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
headerRange.Font.Size = 10;
headerRange.Text = "Header text goes here";
}
//Add the footers into the document
foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
{
//Get the footer range and add the footer details.
Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
footerRange.Font.Size =10;
footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
footerRange.Text = "Footer text goes here";
}
//adding text to document
document.Content.SetRange(0, 0);
document.Content.Text = "This is test document "+ Environment.NewLine;
//Add paragraph with Heading 1 style
Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
object styleHeading1 = "Heading 1";
para1.Range.set_Style(ref styleHeading1);
para1.Range.Text = "Para 1 text";
para1.Range.InsertParagraphAfter();
//Add paragraph with Heading 2 style
Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
object styleHeading2 = "Heading 2";
para2.Range.set_Style(ref styleHeading2);
para2.Range.Text = "Para 2 text";
para2.Range.InsertParagraphAfter();
//Create a 5X5 table and insert some dummy record
Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);
firstTable.Borders.Enable = 1;
foreach (Row row in firstTable.Rows)
{
foreach (Cell cell in row.Cells)
{
//Header row
if (cell.RowIndex == 1)
{
cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
cell.Range.Font.Bold = 1;
//other format properties goes here
cell.Range.Font.Name = "verdana";
cell.Range.Font.Size = 10;
//cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
//Center alignment for the Header cells
cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
//Data row
else
{
cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
}
}
}
//Save the document
object filename = @"c:\temp1.docx";
document.SaveAs2(ref filename);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
winword = null;
MessageBox.Show("Document created successfully !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Ещё посмотрите это :
Вот класс работы с документом.
Посмотрите здесь на //Создаем документ
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Word = Microsoft.Office.Interop.Word;
using InfoPath = Microsoft.Office.Interop.InfoPath;
namespace MSOffice
{
public class cWord : cOffice
{
Word.Application wordapp;
Word.Document worddocument;
DataTable table;
Word.WdReplace replace = Word.WdReplace.wdReplaceOne;
public cWord()
{
//Создаем объект Word - равносильно запуску Word
wordapp = new Word.Application();
}
public override void OpenFile(string sTemplate, XmlDocument xmlDoc)
{
try
{
fProcess process = new fProcess();
XmlNodeList xnl = xmlDoc.SelectNodes("/root[@type=\"table\"]");
if (xnl.Count != 0)
{
//Делаем его видимым
Object template = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), sTemplate);
Object newTemplate = false;
Object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
Object visible = true;
//Создаем документ
worddocument = wordapp.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
wordapp.Visible = true;
int tables = worddocument.Tables.Count;
replace = Word.WdReplace.wdReplaceAll;
SearchAndReplace("$YN$", DateTime.Now.Year.ToString());
replace = Word.WdReplace.wdReplaceOne;
if (tables != 0)
{
//process.Show();
for (int idx = 1; idx <= worddocument.Tables.Count; idx++)
{
xnl = xmlDoc.SelectNodes("//table");
for (int index = 0; index < xnl.Count; index++)
{
XmlNodeList xnl2 = xnl[index].SelectNodes("//row");
bool change = false;
Word.Range rng = null;
for (int i = 0; i < xnl2.Count; i++)
{
if (!change)
{
rng = worddocument.Tables[idx].Rows[2].Range;
rng.Font.Size = 12;
rng.Font.Name = "New Time Romand";
rng.Font.Bold = 0;
rng.Select();
rng.Copy();
change = true;
}
object start = worddocument.Tables[idx].Range.End;
object end = worddocument.Tables[idx].Range.End;
rng = worddocument.Range(ref start, ref end);
SearchAndReplace("##", (i + 1).ToString());
for (int j = 0; j < xnl2[i].ChildNodes.Count; j++)
{
SearchAndReplace("$" + xnl2[i].ChildNodes[j].Attributes[0].InnerText + "$", xnl2[i].ChildNodes[j].InnerText);
}
if (i != (xnl2.Count - 1))
rng.Paste();
}
}
}
CloseDoc(worddocument);
//process.Close();
}
xnl = xmlDoc.SelectNodes("//root");
for (int i = 0; i < xnl.Count; i++)
{
for (int j = 0; j < xnl[i].ChildNodes.Count; j++)
{
if (xnl[i].ChildNodes[j].Name.CompareTo("table") != 0)
SearchAndReplace("$" + xnl[i].ChildNodes[j].Name + "$", xnl[i].ChildNodes[j].InnerText);
}
}
}
xnl = xmlDoc.SelectNodes("/root[@type=\"single\"]");
if (xnl.Count != 0)
{
xnl = xmlDoc.SelectNodes("//document");
process.Show();
for (int i = 0; i < xnl.Count; i++)
{
process.pbProc.Value = (i + 1) * 100 / xnl.Count;
//Делаем его видимым
Object template = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), sTemplate);
Object newTemplate = false;
Object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
Object visible = true;
//Создаем документ
worddocument = wordapp.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
wordapp.Visible = true;
replace = Word.WdReplace.wdReplaceAll;
SearchAndReplace("$YN$", DateTime.Now.Year.ToString());
replace = Word.WdReplace.wdReplaceOne;
XmlNodeList xnl2 = xnl[i].SelectNodes("item[@name=\"fioStudH\"]");
string name = "";
if (xnl2.Count != 0)
name = xnl2[0].InnerText;
for (int j = 0; j < xnl[i].ChildNodes.Count; j++)
{
if (xnl[i].ChildNodes[j].Attributes[0].Value.CompareTo("SCode") == 0 || xnl[i].ChildNodes[j].Attributes[0].Value.CompareTo("SpecialityC") == 0)
replace = Word.WdReplace.wdReplaceAll;
else
replace = Word.WdReplace.wdReplaceOne;
SearchAndReplace("$" + xnl[i].ChildNodes[j].Attributes[0].Value + "$", xnl[i].ChildNodes[j].InnerText);
}
replace = Word.WdReplace.wdReplaceAll;
for (int j = 0; j < xnl[i].ChildNodes.Count; j++)
{
SearchAndReplace("$" + xnl[i].ChildNodes[j].Attributes[0].Value + "$", "");
}
xnl2 = xmlDoc.SelectNodes("/root/filename");
this.SaveDocument(string.Format("{0} {1}", xnl2[0].Attributes[0].Value, name));
CloseDoc(worddocument);
}
process.Close();
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
Close();
return;
}
}
public void AddDocument(string sTemplate, XmlDocument xmlDoc)
{
}
private void CloseDoc(Word.Document worddocument)
{
Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
Object originalFormat = Type.Missing;
Object routeDocument = Type.Missing;
((Word._Document)worddocument).Close(ref saveChanges, ref originalFormat, ref routeDocument);
}
public void SaveDocument(string strFileName)
{
Object fileName = string.Format("{1}\\Documents\\{0}.doc", strFileName, Directory.GetCurrentDirectory());
Object fileFormat = Type.Missing;
Object lockComments = Type.Missing;
Object password = Type.Missing;
Object addToRecentFiles = Type.Missing;
Object writePassword = Type.Missing;
Object readOnlyRecommended = Type.Missing;
Object embedTrueTypeFonts = Type.Missing;
Object saveNativePictureFormat = Type.Missing;
Object saveFormsData = Type.Missing;
Object saveAsAOCELetter = Type.Missing;
Object encoding = Type.Missing;
Object insertLineBreaks = Type.Missing;
Object allowSubstitutions = Type.Missing;
Object lineEnding = Type.Missing;
Object addBiDiMarks = Type.Missing;
worddocument.SaveAs(ref fileName, ref fileFormat, ref lockComments,
ref password, ref addToRecentFiles, ref writePassword,
ref readOnlyRecommended, ref embedTrueTypeFonts,
ref saveNativePictureFormat, ref saveFormsData,
ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,
ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);
}
/// <summary>
/// Поиск и замена текста
/// </summary>
public void SearchAndReplace(string find, string replace)
{
try
{
// Смещаем выделение к началу документа
object Start = 0;
object End = worddocument.Paragraphs[worddocument.Paragraphs.Count].Range.End;
Word.Range rng = worddocument.Range(ref Start, ref End);
Word.Find fnd = rng.Find;
fnd.ClearFormatting();
fnd.Text = find;
fnd.Replacement.ClearFormatting();
fnd.Replacement.Text = replace;
ExecuteReplace(fnd);
}
catch (Exception exp)
{
System.Windows.Forms.MessageBox.Show(exp.Message);
return;
}
}
private Boolean ExecuteReplace(Word.Find find)
{
return ExecuteReplace(find, replace);
}
private Boolean ExecuteReplace(Word.Find find, Object replaceOption)
{
// Простая оболочка Find.Execute:
Object findText = Type.Missing;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = Type.Missing;
Object wrap = Type.Missing;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = replaceOption;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing;
return find.Execute(ref findText, ref matchCase,
ref matchWholeWord, ref matchWildcards, ref matchSoundsLike,
ref matchAllWordForms, ref forward, ref wrap, ref format,
ref replaceWith, ref replace, ref matchKashida,
ref matchDiacritics, ref matchAlefHamza, ref matchControl);
}
//
public void SetData(DataTable table)
{
this.table = table;
}
public override void EditFile()
{
throw new Exception("The method or operation is not implemented.");
}
public override void SaveFile()
{
throw new Exception("The method or operation is not implemented.");
}
public void Close()
{
// Выводим запрос на сохранение изменений
Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
Object originalFormat = Type.Missing;
Object routeDocument = Type.Missing;
((Word._Application)wordapp).Quit(ref saveChanges,
ref originalFormat, ref routeDocument);
}
}
}
Для docx есть DocX https://docx.codeplex.com/
using Novacode; // предварительно добавив в проект ссылку на dll
...
DocX DocX1;
...
DocX1 = DocX.Load("путь к файлу");
...
for (int i = 0; i < DocX1.Paragraphs.Count; i++)
{
RichTextBox1.Text += DocX1.Paragraphs[i].Text + Environment.NewLine;
}
...
DocX1.Save(); // можно ещё внести какие-то изменения в docx, скажем, добавить абзац с помощью DocX1.InsertParagraph, и сохранить.
Виртуальный выделенный сервер (VDS) становится отличным выбором
Пользуюсь библиотекой Spreadsheetgear 2009Как отключить копирование перетаскиванием, нажатием левой кнопки мышки за точку в правом нижнем углу ячейки
Не могу понять в чем причинаНа моей машине подключение к серверу происходит на ура