Export data to word in c# - c#

Below is the code that creates a pdf to write a file..Every time i call the below code it creates a pdf file to write into..My question is,is there a same method for exporting to word or for simplicity just creates a blank doc file so that i can export data into it..
public void showPDf() {
iTextSharp.text.Document doc = new iTextSharp.text.Document(
iTextSharp.text.PageSize.A4);
string combined = Path.Combine(txtPath.Text,".pdf");
PdfWriter pw = PdfWriter.GetInstance(doc, new FileStream(combined, FileMode.Create));
doc.Open();
}

1. Interop API
It is available in Namespace Microsoft.Office.Interop.Word.
You can use Word Interop COM API to do that using following code,
// Open a doc file.
Application application = new Application();
Document document = application.Documents.Open("C:\\word.doc");
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
Console.WriteLine("Word {0} = {1}", i, text);
}
// Close word.
application.Quit();
Only Drawback is you must have office installed to use this feature.
2. OpenXML
you can use openxml to build word documents, try the following link,
http://msdn.microsoft.com/en-us/library/bb264572(v=office.12).aspx

Did you try searching the web for this ?
How to automate Microsoft Word to create a new document by using Visual C#

There is a free solution to export data to word,
http://www.codeproject.com/Articles/151789/Export-Data-to-Excel-Word-PDF-without-Automation-f

Related

Creating word add in with OpenXML to insert new MergeField

I'm new to VSTO and OpenXML and I would like to develop a Word add-in. This add-in should use OpenXML, The add in should add a MergeField to the document, I can actually add MergeField using ConsoleApp but I want to insert the MergeField from the Word add in to the current opened document.
So I have this code in ButtonClick
// take current file location
var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);
// function to insert new field here
OpenAndAddTextToWordDocument(fileFullName, "username");
Globals.ThisAddIn.Application.Documents.Open(fileFullName);
And I Created the function which should add the new MergeField:
public static DocumentFormat.OpenXml.Wordprocessing.Paragraph OpenAndAddTextToWordDocument(string filepath, string txt)
{
// Open a WordprocessingDocument for editing using the filepath.
WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(filepath, true);
// Assign a reference to the existing document body.
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
// add text
string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", txt);
SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Text text1 = new Text();
text1.Text = String.Format("«{0}»", txt);
run1.Append(runProperties1);
run1.Append(text1);
simpleField1.Append(run1);
DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
paragraph.Append(new OpenXmlElement[] { simpleField1 });
return paragraph;
// Close the handle explicitly.
wordprocessingDocument.Close();
But something is not working here, when I use the add in it doesn't do anything
Thanks for the help.
Add a try/catch and you'll probably find that it can't open the file because it's currently open for editing.
The OpenXML SDK is a library for writing to Office files without going through Office's interfaces. But you're trying to do so while also using Office's interfaces, so you're essentially trying to take two approaches at once. This isn't going to work unless you first close the document.
But what you probably want to do is use VSTO. In VSTO, each document has a Fields collection, that you can use to add fields.
Fields.Add(Range, Type, Text, PreserveFormatting)

Replace a bookmark in a Word document with the contents of another word document

I'm looking to replace a bookmark in a word document with the entire contents of another word document. I was hoping to do something along the lines of the following, but appending the xml does not seem to be enough as it does not include pictures.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application wordApp = new Word.Application();
Word.Document doc = wordApp.Documents.Add(filename);
var bookmark = doc.Bookmarks.OfType<Bookmark>().First();
var doc2 = wordApp.Documents.Add(filename2);
bookmark.Range.InsertXML(doc2.Contents.XML);
The second document contains a few images and a few tables of text.
Update: Progress made by using XML, but still doesn't satisfy adding pictures as well.
You've jumped in deep.
If you're using the object model (bookmark.Range) and trying to insert a picture you can use the clipboard or bookmark.Range.InlineShapes.AddPicture(...). If you're trying to insert a whole document you can copy/paste the second document:
Object objUnit = Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref objUnit, ref oMissing);
wordApp.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);
If you're using XML there may be other problems, such as formatting, images, headers/footers not coming in correctly.
Depending on the task it may be better to use DocumentBuilder and OpenXML SDK. If you're writing a Word addin you can use the object API, it will likely perform the same, if you're processing documents without Word go with OpenXML SDK and DocumentBuilder. The issue with DocumentBuilder is if it doesn't work there aren't many work-arounds to try. It's open source not the cleanest piece of code if you try troubleshooting it.
You can do this with openxml SDK and Document builder. To outline here is what you will need
1> Inject insert key in main doc
public WmlDocument GetProcessedTemplate(string templatePath, string insertKey)
{
WmlDocument templateDoc = new WmlDocument(templatePath);
using (MemoryStream mem = new MemoryStream())
{
mem.Write(templateDoc.DocumentByteArray, 0, templateDoc.DocumentByteArray.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open([source], true))
{
XDocument xDoc = doc.MainDocumentPart.GetXDocument();
XElement bookMarkPara = [get bookmarkPara to replace];
bookMarkPara.ReplaceWith(new XElement(PtOpenXml.Insert, new XAttribute("Id", insertKey)));
doc.MainDocumentPart.PutXDocument();
}
templateDoc.DocumentByteArray = mem.ToArray();
}
return templateDoc;
}
2> Use document builder to merge
List<Source> documentSources = new List<Source>();
var insertKey = "INSERT_HERE_1";
var processedTemplate = GetProcessedTemplate([docPath], insertKey);
documentSources.Add(new Source(processedTemplate, true));
documentSources.Add(new Source(new WmlDocument([docToInsertFilePath]), insertKey));
DocumentBuilder.BuildDocument(documentSources, [outputFilePath]);

Convert docx to pdf

My documents are stored in a database that I want to send mail with attachments.
I want to convert stored docx to pdf.
var result = from c in valinor.documents
select new
{
c.document_name,
c.document_size,
c.document_content
};
var kk = result.ToList();
for (int i = 0; i<kk.Count; i++)
{
MemoryStream stream = new MemoryStream(kk[i].document_content);
Attachment attachment = new Attachment(stream, kk[i].document_name + ".pdf", "application/pdf");
mail.Attachments.Add(attachment);
}
How can I convert document_content to pdf?
You need to use Microsoft.Office.Interop.Word in MIcrosoft office dll.
add reference to your project Microsoft.Office.Interop.Word
Check my sample of Code.
It's nice and Easy. 100% work for me.
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
wordDocument = word.Documents.Open(savedFileName, ReadOnly: true);
wordDocument.ExportAsFixedFormat(attahcmentPath + "/pdf" + attachment.BetAttachmentCode + ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
word.Quit(false);
You will need a third party component such as ABCpdf and (probably) Word installed on the machine and use that component to convert from docx to pdf.

Embed an Excel graphic in a Word document with OpenXML working with Word 2010 and 2003

I have to implement a Microsoft Word document generator with embed excel graphics in it.
One of my constraint is to make my generated docx work both with Microsoft word 2010 and 2003 + compatibility pack.
I didn't managed to make it works for both of them. I can make it works for Word 2010 but the document are not working for 2003 and vice versa.
After several search to make it work for Word 2003 I have added this in my code :
private static void Word2003(ChartPart importedChartPart, MainDocumentPart mainDocumentPart, Stream fileStream)
{
var ext = new ExternalData { Id = "rel" + 5 };
importedChartPart.ChartSpace.InsertAt(ext, 3);
var fi = new FileInfo(#"generated.xlsx");
importedChartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", new Uri(fi.Name, UriKind.Relative), "rel5");
EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddEmbeddedPackagePart(#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Stream copyStream = new MemoryStream();
fileStream.CopyTo(copyStream);
embeddedObjectPart.FeedData(copyStream);
}
But at this point generated documents don't work with Word 2010. If I delete these two lignes :
var ext = new ExternalData { Id = "rel" + 5 };
importedChartPart.ChartSpace.InsertAt(ext, 3);
from previous code it's works for Word 2010 but not for Word 2003.
I have tried several things but I didn't manage to make it work for each case.
You can find this small piece of code here
The prerequisite is a template of Excel file with a Chart and a graphic in it.
Edit : Generated document always works with Microsoft Office 2007 (with the two problematic code lines or not). I'm still seeking for solutions !
I finally found the solution !
The problem was due to 2 things :
I didn't put the External Data correctly and the External relationship was wrong.
This code make it works :
private static void Word2003(ChartPart importedChartPart, MainDocumentPart mainDocumentPart, Stream fileStream)
{
// Add of the external data id
ExternalData ext = new ExternalData { Id = "rel" + 5 };
AutoUpdate autoUpdate = new AutoUpdate{ Val = false};
ext.Append(autoUpdate);
importedChartPart.ChartSpace.Append(ext);
// Set of the relationship
var fi = new FileInfo(#"generated.xlsx");
importedChartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject", new Uri(fi.Name, UriKind.Relative), "rel5");
// Link to the embedded file
EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddEmbeddedPackagePart(#"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Stream copyStream = new MemoryStream();
fileStream.CopyTo(copyStream);
embeddedObjectPart.FeedData(copyStream);
}
Now generated Word document works with Word 2003, 2007 and 2010.
Maybe this will help somebody!

Populate a word template using C# in ASP.NET MVC3

I read it some post referring to Populate word documents, but I need to populate a word document (Office 2007) using C#. For example i want to have a word document with a label [NAME], use that label in C# to put my value, and do all this in a ASP.NET MVC3 controller. Any idea?
You could use the OpenXML SDK provided by Microsoft to manipulate Word documents. And here's a nice article (it's actually the third of a series of 3 articles) with a couple of examples.
You can do like this :
- Introduce "signets" into your Word document template
- Work on a copy of your word template
- Modify signets values from c# code and save or print your file.
Be carefull with releasing correctly your word process if you treat several documents in your application :)
OP's solution extracted from the question:
The solution i found is this:
static void Main(string[] args)
{
Console.WriteLine("Starting up Word template updater ...");
//get path to template and instance output
string docTemplatePath = #"C:\Users\user\Desktop\Doc Offices XML\earth.docx";
string docOutputPath = #"C:\Users\user\Desktop\Doc Offices XML\earth_Instance.docx";
//create copy of template so that we don't overwrite it
File.Copy(docTemplatePath, docOutputPath);
Console.WriteLine("Created copy of template ...");
//stand up object that reads the Word doc package
using (WordprocessingDocument doc = WordprocessingDocument.Open(docOutputPath, true))
{
//create XML string matching custom XML part
string newXml = "<root>" +
"<Earth>Outer Space</Earth>" +
"</root>";
MainDocumentPart main = doc.MainDocumentPart;
main.DeleteParts<CustomXmlPart>(main.CustomXmlParts);
//MainDocumentPart mainPart = doc.AddMainDocumentPart();
//add and write new XML part
CustomXmlPart customXml = main.AddCustomXmlPart(CustomXmlPartType.CustomXml);
using (StreamWriter ts = new StreamWriter(customXml.GetStream()))
{
ts.Write(newXml);
}
//closing WordprocessingDocument automatically saves the document
}
Console.WriteLine("Done");
Console.ReadLine();
}

Categories