Всем привет, как сделать экспорт данных в WPF из DataGrid в Microsfot office word, использую Microsoft.Office.Interop.Word. Делал шаблон документа и заменял значения через код, как тоже самое сделать с таблицей брав данные из DataGrid?
задан 29 апр 2020 в 9:40
Если нужно перенести данные в Ворд из ДатаГрида, при этом и нарисовать таблицу в ворде то нет такого пути, реализовать который можно 2 строками. Придется через средства библиотеки mocrosoft.interop.word рисовать, а потом переносить туда данные. Если же надо просто перелить в ворд в строку данные из таблицы, то банальный перебор всех ячеек в одну переменную и заливка этого добра в документ. Уточните, вам нужно таблицу в ворде делать?
ответ дан 29 апр 2020 в 9:57
5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
private void ToForm_Click(object sender, RoutedEventArgs e) { var datehelp = Convert.ToDateTime(DateHelpDP.SelectedDate.Value.ToShortDateString()); var Lastname = LastNameTB.Text; var Firstname = FirstTB.Text; var Middlename = MiddleNameTB.Text; var Dateofbirtth = Convert.ToDateTime(DateofBirthDP.SelectedDate.Value.ToShortDateString()); var Enroll = Convert.ToDateTime(EnrollDP.SelectedDate.Value.ToShortDateString()); var Group = GroupTB.Text; var Speciality = SpecialtyTB.Text; var DatePeriod = DatePeriodTB.Text; var EnrollmentDate = Convert.ToDateTime(EnrollmentDateDP.SelectedDate.Value.ToShortDateString()); var EnrollmentNumber = EnrollmentNumberTB.Text; var EnrollStudent = Convert.ToDateTime(EnrollStudentDP.SelectedDate.Value.ToShortDateString()); var orderReleasedDate = Convert.ToDateTime(ReleaseDate.SelectedDate.Value.ToShortDateString()); var NumberReleased = ReleaseNumberTB.Text; var Series = SeriesTB.Text; var Number = NumberTB.Text; var ApplicationDate = Convert.ToDateTime(ApplicationDateDP.SelectedDate.Value.ToShortDateString()); var RegistrationNumber = RegistrationNumberTB.Text; var wordApp = new Word.Application(); wordApp.Visible = false; try { var wordDoucument = wordApp.Documents.Open(TemplateFileName); ReplaceWordStub("{datehelp}", Convert.ToString(datehelp.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{lastname}", Lastname, wordDoucument); ReplaceWordStub("{firstname}", Firstname, wordDoucument); ReplaceWordStub("{middlename}", Middlename, wordDoucument); ReplaceWordStub("{dateofbirtth}", Convert.ToString(Dateofbirtth.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{enrolldate}", Convert.ToString(Enroll.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{group}", Group, wordDoucument); ReplaceWordStub("{speciality}", Speciality, wordDoucument); ReplaceWordStub("{dateperiod}", DatePeriod, wordDoucument); ReplaceWordStub("{EnrollmentrDate}", Convert.ToString(EnrollmentDate.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{EnrollmentNumber}", EnrollmentNumber, wordDoucument); ReplaceWordStub("{enrollstudent}", Convert.ToString(EnrollStudent.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{lastname}", Lastname, wordDoucument); ReplaceWordStub("{firstname}", Firstname, wordDoucument); ReplaceWordStub("{middlename}", Middlename, wordDoucument); ReplaceWordStub("{speciality}", Speciality, wordDoucument); ReplaceWordStub("{orderReleasedDate}", Convert.ToString(orderReleasedDate.ToString("dd.MM.yy")), wordDoucument); ReplaceWordStub("{NumberReleased}", NumberReleased, wordDoucument); ReplaceWordStub("{seria}", Series, wordDoucument); ReplaceWordStub("{number}", Number, wordDoucument); ReplaceWordStub("{DiplomaDate}", Convert.ToString(ApplicationDate.ToShortDateString()), wordDoucument); ReplaceWordStub("{RegistrationNumber}", RegistrationNumber, wordDoucument); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".docx"; // Default file extension Nullable<bool> result = dlg.ShowDialog(); string filename = ""; if (result == true) { filename = dlg.FileName; } wordDoucument.SaveAs(filename); wordApp.Visible = true; wordDoucument = null; } catch { MessageBox.Show("Ошибка заполнения "); } } |
-
Home -
Software Programming -
WPF C# Data Export DataGrid in Word
This topic has been deleted. Only users with topic management privileges can see it.
-
Hey, everybody, how to make data exports to WPF from DataGrid in Microsfot office word, use Microsoft.Office.Interop.Word. Doing the document template and replacing it with the code, how do you do the data from the DataGrid table?
-
If the data are to be transferred to the Ward from the date of Grid and the table painted in the ward, there is no such route that can be implemented by two lines. We’ll have to draw through the mocrosoft library. If we just need to put the data from the table into the horde, then the banal bulkhead of all the cells into one variable and the tidal of this kind into a document. Are you going to need a table in the warden?
Suggested Topics
-
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views
Looking to add functionality in your .NET apps to export data to Word and PDF? Learn four ways to do this with just a little code.
Building feature rich applications can often leave users asking to take visual elements off the screen to be used elsewhere. Being able to export from an application to Word or PDF opens up new possibilities, such as sharing, reporting or even satisfying Sarbanes–Oxley (SOX) audit requirements.
Getting data out of your application and into standard formats like Microsoft Word and Adobe PDF can be a daunting task. Especially when performance optimizations for large datasets, document customization & appearance, and supported platforms are taken into consideration.
However, with the right tools, adding this feature to your .NET application can be as simple as a few lines of code. Let’s take a look at 4 ways we can include rich document functionality in our .NET apps with very little code and time investment.
For the examples we’ll be using the Telerik Document Processing Library (DPL), which is distributed at no additional cost with the Progress Telerik UI libraries for WPF, Silverlight and WinForms. For the web developers out there, the DPL is also included with ASP.NET Web Forms and MVC. In addition, no MS Office licenses or dependencies are required to use the DPL.
If you’re using Telerik UI, you already have these capabilities in your toolbox and we’ll learn how to leverage them. If you’re not using Telerik UI yet, but would like to increase your developer productivity, learn more about it here.
1. Create New Word Document in .NET
Having the ability to create a new Word document from code provides a great deal of flexibility. With a just few dependencies we have access to Word document creation APIs that include text, image, and link generation. For this example, we’ll use RadFlowDocument
and RadFlowDocumentEditor
to create a new Word document from a .NET console application.
We’ll start with a few dependencies like System.IO
to handle a file stream, and the necessary Telerik DPL assemblies.
using
System.IO;
using
Telerik.Windows.Documents.Flow.FormatProviders.Docx;
using
Telerik.Windows.Documents.Flow.Model;
using
Telerik.Windows.Documents.Flow.Model.Editing;
Next, we create a new RadFlowDocument
and RadFlowDocumentEditor
. The RadFlowDocumentEditor
will allow us to insert new text, image and other elements to the document.
static
void
Main(
string
[] args)
{
RadFlowDocument document =
new
RadFlowDocument();
RadFlowDocumentEditor editor =
new
RadFlowDocumentEditor(document);
Using the editor, we’ll write some text to the document using the InsertText
method. We also have additional methods available such as:
- InsertFloatingImage
- InsertParagraph
- InsertTable
- InsertHyperlink
- and more
static
void
Main(
string
[] args)
{
RadFlowDocument document =
new
RadFlowDocument();
RadFlowDocumentEditor editor =
new
RadFlowDocumentEditor(document);
editor.InsertText(
"Hello Word!"
);
Once the document is complete, we just need to write it to the FileStream
. For the RadFlowDocument
we’ll use the DocxFormatProvider
to export to the DOCX format. Similarly, we could use a PdfFormatProvider
to create a PDF document.
using
System.IO;
using
Telerik.Windows.Documents.Flow.FormatProviders.Docx;
using
Telerik.Windows.Documents.Flow.Model;
using
Telerik.Windows.Documents.Flow.Model.Editing;
namespace
DocProcessing
{
class
Program
{
static
void
Main(
string
[] args)
{
RadFlowDocument document =
new
RadFlowDocument();
RadFlowDocumentEditor editor =
new
RadFlowDocumentEditor(document);
editor.InsertText(
"Hello Word!"
);
using
(Stream output =
new
FileStream(
"output.docx"
, FileMode.OpenOrCreate))
{
DocxFormatProvider provider =
new
DocxFormatProvider();
provider.Export(document, output);
}
}
}
}
In this example, files created using the Telerik DPL are saved directly to disk. However, any file created using the DPL can also be downloaded via the browser from UI for ASP.NET AJAX and UI for ASP.NET MVC applications.
2. Mail Merge from .NET
Creating a mail merge is an effective way of building a template and populating it with data for processing documents in batches. With the mail merge process, you can create a series of personalized documents based on your data source.
The mail merge process is one that is often manually performed inside of Microsoft Word. With the Telerik DPL this process can be completely automated and customized based on the needs of your application. The mail merge APIs can be used virtually anywhere in .NET. To see it in action we’ll use an example of how a mail merge is executed in a WPF/WinForms application.
We’ll create a new document containing our template message. To create a template field in the document we’ll use the InsertField
method and set the field code to MERGEFIELD
with the variable name we wish to use, in this case FirstName
. The variable name simply matches the property on an object that we’ll supply to the MailMerge
method.
private
RadFlowDocument CreateDocument()
{
RadFlowDocument document =
new
RadFlowDocument();
RadFlowDocumentEditor editor =
new
RadFlowDocumentEditor(document);
editor.InsertText(
"Dear "
);
editor.InsertField(
"MERGEFIELD FirstName"
,
""
);
editor.InsertText(
" "
);
editor.InsertField(
"MERGEFIELD LastName"
,
""
);
editor.InsertLine(
","
);
editor.InsertLine(
"This is a sample Mail Merge"
);
return
document;
}
With the document created, the next step will be to perform the mail merge. The MailMerge
method takes any IEnumerable
as a parameter, in this case we’ll use a predefined list of Person
via GetRecipents
. In this case Person
has a FirstName
and LastName
property matching the MERGEFIELD
variables.
protected
void
button_Click(
object
sender, EventArgs e)
{
RadFlowDocument document =
this
.CreateDocument();
RadFlowDocument mailMergeDocument = document.MailMerge(GetRecipients());
//save the document
}
The document can be saved by setting up a MemoryStream
and calling Export
from a DocxFromatProvider
. Once the memory stream is ready, we’ll write it to a file.
protected
void
button_Click(
object
sender, EventArgs e)
{
RadFlowDocument document =
this
.CreateDocument();
RadFlowDocument mailMergeDocument = document.MailMerge(GetRecipients());
byte
[] renderedBytes =
null
;
using
(Stream output =
new
FileStream(
"output.docx"
, FileMode.OpenOrCreate))
{
DocxFormatProvider provider =
new
DocxFormatProvider();
provider.Export(mailMergeDocument, output);
}}
The result is a multi-page .DOCX file for each recipient provided to the mail merge. This type of document can easily be printed and sent to clients as physical mail. See demos.telerik.com/wpf and the UI for WinForms demos for a more comprehensive example that includes additional file types and document features.
3. Convert Word to PDF in .NET
One of the Telerik DPL strengths is its ability to import and export various file types like: DOCX, PDF (export only), HTML and RTF. Because of this ability, it can also be used to do file conversions between these types as well. Using the IFormatProvider
we can utilize the various format providers within the Telerik DPL interchangeably. Let’s take a look at a basic example of a console app that can import a DOCX file and export it to PDF.
We’ll begin by creating a default provider using an IFormatProvider
and setting it to an instance of DocxFormatProvider
. A RadFlowDocument
is used as our document in the conversion from DOCX to PDF.
IFormatProvider<RadFlowDocument> fileFormatProvider =
new
DocxFormatProvider();
RadFlowDocument documentToConvert =
new
RadFlowDocument();
The DOCX document is opened from disk using the DocxFormatProvider
and streamed into memory.
using
(FileStream input =
new
FileStream(
"input.docx"
, FileMode.Open))
{
documentToConvert = fileFormatProvider.Import(input);
}
With the document in memory as a RadFlowDocument
we can change our provider from a DocxFormatProvider
PdfFormatProvider
. Now the document can be written back to disk as a PDF.
fileFormatProvider =
new
PdfFormatProvider();
using
(Stream output =
new
FileStream(
"output.pdf"
, FileMode.OpenOrCreate))
{
fileFormatProvider.Export(documentToConvert, output);
}
As you can see in the complete example, in just a few short lines of code we’re able to convert from DOCX to PDF.
static
void
Main(
string
[] args)
{
IFormatProvider<RadFlowDocument> fileFormatProvider =
new
DocxFormatProvider();
RadFlowDocument documentToConvert =
new
RadFlowDocument();
// Read DOCX
using
(FileStream input =
new
FileStream(
"input.docx"
, FileMode.Open))
{
documentToConvert = fileFormatProvider.Import(input);
}
// Write PDF
fileFormatProvider =
new
PdfFormatProvider();
// change format provider to PDF
using
(Stream output =
new
FileStream(
"output.pdf"
, FileMode.OpenOrCreate))
{
fileFormatProvider.Export(documentToConvert, output);
}
}
This method of importing and exporting documents can be used to convert between file formats. One caveat however is that there is no import functionality for PDF documents due to file format limitations. To deal with this limitation the IFormatProvider
is equipped with a CanImport
property that can be checked before the Import
operation is performed.
See the UI for WPF and UI for WinForms WordsProcessing demos that includes additional file types and scenarios.
4. Edit Microsoft Word Docs in WPF and WinForms
Customers can sometimes ask for time-consuming project requirements, like the ability to edit Word Documents in the application without the need to leave the app and use external editors. On the surface this sounds like a feature that will take quite a bit of effort to accomplish; however, it’s as simple as adding a rich text component to your application which comes with the Telerik UI for WPF and Telerik UI for WinForms suites.
Using UI for WPF and UI for WinForms, the ability to import and export right from the rich text editor control can be accomplished with few lines of code.
DocxFormatProvider provider =
new
DocxFormatProvider();
using
(FileStream fileStream =
new
FileStream(@
"input.docx"
, FileMode.Open))
{
this
.radRichTextBox1.Document = provider.Import(fileStream);
})
Exporting the content is just as simple. Simply pick the format provider for the desired format – PDF, DOCX, XAML, HTML, RTF, TXT and utilize its Export() method.
DocxFormatProvider provider =
new
DocxFormatProvider();
SaveFileDialog saveDialog =
new
SaveFileDialog() { DefaultExt =
".docx"
, Filter =
"Documents|*.docx"
};
DialogResult dialogResult = saveDialog.ShowDialog();
if
(dialogResult == System.Windows.Forms.DialogResult.OK)
{
using
(Stream output = saveDialog.OpenFile())
{
provider.Export(radRichTextEditor1.Document, output);
}
}
See the Telerik UI for WPF and Telerik UI for WinForms demos for more comprehensive examples that include additional editor features.
Conclusion
Whether you need to create documents from scratch or edit in the desktop app, the Telerik UI libraries make short work of any document export task for .NET developers. With the Telerik Document Processing Library new files can be created from scratch as DOCX, PDF, RTF, or TXT. Advanced features such as mail merge can reduce manual tasks with app driven automation. With the addition of Telerik UI libraries powered by UI for WPF and WinForms, documents can be edited on screen and custom export features empower users to export content with the click of a button.
Get access to the vast benefits of Telerik Document Processing and document exporting by downloading either the full Progress DevCraft bundle or any technology-specific library you need: Telerik UI for WPF or Telerik UI for WinForms.
Other Useful Resources
- SpreadProcessing — Complete Solution to Create, Modify and Export Spreadsheets -Part I
- Getting Started with RadPdfProcessing in Telerik UI for WinForms
- Getting Started with WordProcessing in UI for WinForms Vol.1
Всем привет, как сделать экспорт данных в WPF из DataGrid в Microsfot office word, использую Microsoft.Office.Interop.Word. Делал шаблон документа и заменял значения через код, как тоже самое сделать с таблицей брав данные из DataGrid?
Ответы (1 шт):
Автор решения: GromWolf
Если нужно перенести данные в Ворд из ДатаГрида, при этом и нарисовать таблицу в ворде то нет такого пути, реализовать который можно 2 строками. Придется через средства библиотеки mocrosoft.interop.word рисовать, а потом переносить туда данные. Если же надо просто перелить в ворд в строку данные из таблицы, то банальный перебор всех ячеек в одну переменную и заливка этого добра в документ. Уточните, вам нужно таблицу в ворде делать?
→ Ссылка