コード例 #1
0
        public void ReplaceBookmarks(string sourceDocPath, string targetDocPath, Dictionary <string, string> bookmarks)
        {
            bool isEditable = true;

            // Don't use open unless you want to change that document too, use CreateFromTemplate instead
            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(sourceDocPath, isEditable))
            {
                var body           = doc.MainDocumentPart.Document.Body;
                var bookmarkStarts = body.Descendants <BookmarkStart>();

                foreach (var header in doc.MainDocumentPart.HeaderParts)
                {
                    var headerBookmarkStarts = header.Header.Descendants <BookmarkStart>();
                    bookmarkStarts = bookmarkStarts.Concat(headerBookmarkStarts);
                }

                foreach (var bookmarkStart in bookmarkStarts)
                {
                    Debug.WriteLine($"bookmarkName={bookmarkStart.Name}");
                    Debug.WriteLine($"bookmarkValue={bookmarkStart.InnerText}");
                    var bookmarkName = bookmarkStart.Name.InnerText;
                    if (bookmarks.ContainsKey(bookmarkName))
                    {
                        replaceBookmarkText(bookmarkStart, bookmarks.GetValueOrDefault(bookmarkName));
                    }
                }
                doc.SaveAs(targetDocPath);
            }
        }
コード例 #2
0
ファイル: Form1.cs プロジェクト: whyang9701/docx_processor
        private void button4_Click(object sender, EventArgs e)
        {
            string filepath  = @"..\..\template\template2.docx";
            string filepath2 = @"..\..\export\export4.docx";

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Body      body  = doc.MainDocumentPart.Document.Body;
                Table     table = body.Elements <Table>().ElementAt(1);
                DataTable dt    = new DataTable();
                dt.Columns.AddRange(new DataColumn[] { new DataColumn("column1"), new DataColumn("column2"), new DataColumn("column3"), new DataColumn("column4") });
                DataRow dr = dt.NewRow();
                dr["column1"] = "google";
                dr["column2"] = "facebook";
                dr["column3"] = "yahoo";
                dr["column4"] = "apple";
                dt.Rows.Add(dr);
                DocProcessor.TableRowInsert(table, dt);
                table = body.Elements <Table>().ElementAt(2);
                dt    = new DataTable();
                dt.Columns.AddRange(new DataColumn[] { new DataColumn("column1"), new DataColumn("column2"), new DataColumn("column3"), new DataColumn("column4") });
                dr            = dt.NewRow();
                dr["column1"] = "google";
                dr["column2"] = "facebook";
                dr["column3"] = "yahoo";
                dr["column4"] = "apple";
                dt.Rows.Add(dr);
                DocProcessor.TableColumnInsert(table, dt);
                doc.SaveAs(filepath2).Close();
            }
        }
コード例 #3
0
        private string GetDocumentBase64(int[] workingLog, string rootDir, string userId)
        {
            var tempDocPath = rootDir + string.Format(_tempPath, userId);

            using (var doc = WordprocessingDocument.CreateFromTemplate(rootDir + _templatePath, true))
            {
                var body = doc.MainDocumentPart.Document.Body;

                foreach (var text in body.Descendants <Text>())
                {
                    if (text.Text.Contains("hrs"))
                    {
                        text.Text = text.Text.Replace("hrs", workingLog.Sum().ToString());
                    }
                }

                doc.SaveAs(tempDocPath).Close();
            }

            using var memoryStream = new MemoryStream(File.ReadAllBytes(tempDocPath));
            var docBase64 = Convert.ToBase64String(memoryStream.ReadAsBytes());

            File.Delete(tempDocPath);
            return(docBase64);
        }
コード例 #4
0
        private Document NewDocument()
        {
            WordprocessingDocument newdoc = WordprocessingDocument.CreateFromTemplate(template);

            wrddoc = newdoc;
            mdp    = newdoc.MainDocumentPart;
            return(mdp.Document);
        }
コード例 #5
0
        /// <inheritdoc />
        public IDisposable Create <T>(T instance, string templateFileName) where T : Document
        {
            var package  = WordprocessingDocument.CreateFromTemplate(templateFileName, false);
            var fileName = string.IsNullOrEmpty(instance.FileName)
        ? Path.Combine(Path.GetTempPath(), $"{instance.GetType().Name} {DateTime.Now:dd.MM.yyyy hh.mm.ss}.docx")
        : instance.FileName;

            instance.Fill(package.MainDocumentPart);
            return(new CreateOpenXmlPackageContext(package.SaveAs(fileName), instance));
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: nanhapy/ConsoleApp
        public static void SearchAndReplace(string document, Parent parent)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.CreateFromTemplate(document))
            {
                string docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                docText = docText.Replace("{order.orderId}", "1111222222222222222")
                          .Replace("{order.customerName}", "盛安德盛安德盛安德盛安德盛安德")
                          .Replace("{order.customerAddress}", "盛安德盛安德盛安德盛安德盛安德Address")
                          .Replace("{order.customerContact}", "小张张")
                          .Replace("{order.customerFaxNumber}", "34565675644545")
                          .Replace("{order.selfName}", "盛安德盛安德盛安德盛安德盛安德")
                          .Replace("{order.signDate}", "1990-10-12")
                          .Replace("{order.endWharf}", "曹妃甸")
                          .Replace("{order.startWharf}", "天津港");

                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }

                Body  bod         = wordDoc.MainDocumentPart.Document.Body;
                Table table       = bod.Descendants <Table>().First(t => t.InnerText.Contains("船名/航次"));
                var   rows        = table.Descendants <TableRow>();
                var   templateRow = table.Descendants <TableRow>().ElementAt(1);
                int   len         = 1;
                while (len <= 10)
                {
                    var newRow = templateRow.CloneNode(true) as TableRow;
                    var cells  = newRow.Descendants <TableCell>();
                    ReplaceTableCellText(cells, "{item.voyage}", "WAN MU CHUN 10/1801");
                    ReplaceTableCellText(cells, "{item.cargo}", "角钢");
                    ReplaceTableCellText(cells, "{item.value}", "300000.00");
                    ReplaceTableCellText(cells, "{item.amount}", "40.00");
                    ReplaceTableCellText(cells, "{item.weight}", "200000.00");
                    ReplaceTableCellText(cells, "{item.bgfUnit}", "100000.00 元/吨");
                    ReplaceTableCellText(cells, "{item.receivable}", "-1474836480.00 元");

                    templateRow.InsertAfterSelf(newRow);
                    len++;
                }
                templateRow.Remove();

                ReplaceBookmarksWithImage(wordDoc, "seal", "minjie-seal.png");

                wordDoc.SaveAs("demo.docx");
            }
        }
コード例 #7
0
        public void CanCreateWordprocessingDocumentFromTemplate()
        {
            using (var packageDocument = WordprocessingDocument.CreateFromTemplate(DocumentTemplatePath))
            {
                var part = packageDocument.MainDocumentPart;
                var root = part.Document;

                packageDocument.SaveAs(DocumentPath).Close();

                // We are fine if we have not run into an exception.
                Assert.True(true);
            }
        }
コード例 #8
0
        public void CanCreateWordprocessingDocumentFromTemplate()
        {
            using (var stream = OpenFile(TestFiles.Templates.Document, FileAccess.ReadWrite))
                using (var packageDocument = WordprocessingDocument.CreateFromTemplate(stream.Path))
                {
                    var part = packageDocument.MainDocumentPart;
                    var root = part.Document;

                    packageDocument.SaveAs(Path.GetTempFileName()).Close();

                    // We are fine if we have not run into an exception.
                    Assert.True(true);
                }
        }
コード例 #9
0
ファイル: Form1.cs プロジェクト: whyang9701/docx-Table-helper
        private void button1_Click(object sender, EventArgs e)
        {
            string    filepath  = @"C:\word_test\template.docx";
            string    filepath2 = @"C:\word_test\1234.docx";
            DataTable dt_f06    = new DataTable();
            DataTable dt_f06s   = new DataTable();
            DataTable dt_f06d   = new DataTable();



            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Table table6 = doc.MainDocumentPart.Document.Body.Elements <Table>().ElementAt <Table>(3);
                foreach (DataRow dr_f06 in dt_f06.Rows)
                {
                    string    groupID = dr_f06.Field <object>("GroupID").ToString();
                    DataRow[] a       = dt_f06s.Select(string.Format(("GroupID = '{0}'"), groupID));

                    DataTable dt = new DataTable();
                    dt.Columns.AddRange(new DataColumn[] { new DataColumn("major"), new DataColumn("countType"), new DataColumn("firstGrade1")
                                                           , new DataColumn("firstGrade2"), new DataColumn("secondGrade1"), new DataColumn("secondGrade2"), new DataColumn("thirdGrade1"), new DataColumn("thirdGrade2"), new DataColumn("sum") });

                    //mock up
                    dt = new DataTable();
                    dt.Columns.AddRange(new DataColumn[] { new DataColumn("major"), new DataColumn("countType") });
                    DataRow dr = dt.NewRow();
                    dr["major"]     = "普通科";
                    dr["countType"] = "班級數";
                    dt.Rows.Add(dr);
                    dr              = dt.NewRow();
                    dr["major"]     = "普通科";
                    dr["countType"] = "班級數";
                    dt.Rows.Add(dr);
                    dr              = dt.NewRow();
                    dr["major"]     = "普通科";
                    dr["countType"] = "班級數";
                    dt.Rows.Add(dr);
                    //DocProcessor.TableColumnInsert(table6, dt);
                    //DocProcessor.TableRowInsert(table6, dt);
                    //DocProcessor.DeleteTableColumn(table6, 1);
                    //DocProcessor.DeleteTableRow(table6, 5);
                    DocProcessor.DuplicateElement(table6, new Paragraph(new Run(new Break()
                    {
                        Type = BreakValues.Page
                    })));
                    doc.SaveAs(filepath2).Close();
                }
            }
        }
コード例 #10
0
ファイル: Form1.cs プロジェクト: whyang9701/docx_processor
        private void button2_Click(object sender, EventArgs e)
        {
            string filepath  = @"..\..\template\template1.docx";
            string filepath2 = @"..\..\export\export2.docx";

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Body  body  = doc.MainDocumentPart.Document.Body;
                Table table = body.Elements <Table>().ElementAt(0);
                DocProcessor.TableCellMerge(table, 0, 0, 3, 0);
                DocProcessor.TableCellMerge(table, 0, 1, 0, 3);
                DocProcessor.TableCellMerge(table, 4, 4, 6, 6);

                doc.SaveAs(filepath2).Close();
            }
        }
コード例 #11
0
ファイル: Form1.cs プロジェクト: whyang9701/docx_processor
        private void button1_Click(object sender, EventArgs e)
        {
            string filepath  = @"..\..\template\template1.docx";
            string filepath2 = @"..\..\export\export1.docx";

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("aaa", "apple");
                dic.Add("bbb", "Banana");
                dic.Add("ccc", "California");
                dic.Add("ddd", "dog");

                DocProcessor.ReplaceTags(doc.MainDocumentPart.Document.Body, dic);
                doc.SaveAs(filepath2).Close();
            }
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: whyang9701/docx_processor
        private void button3_Click(object sender, EventArgs e)
        {
            string filepath  = @"..\..\template\template2.docx";
            string filepath2 = @"..\..\export\export3.docx";

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Body  body  = doc.MainDocumentPart.Document.Body;
                Table table = body.Elements <Table>().ElementAt(1);
                DocProcessor.DeleteTableColumn(table, 3);
                table = body.Elements <Table>().ElementAt(2);
                DocProcessor.DeleteTableRow(table, 3);


                doc.SaveAs(filepath2).Close();
            }
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: whyang9701/docx_processor
        private void button5_Click(object sender, EventArgs e)
        {
            string filepath  = @"..\..\template\template2.docx";
            string filepath2 = @"..\..\export\export5.docx";

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(filepath))
            {
                Body  body  = doc.MainDocumentPart.Document.Body;
                Table table = body.Elements <Table>().ElementAt(1);
                DocProcessor.DuplicateElement(table);
                table = body.Elements <Table>().ElementAt(3);
                DocProcessor.DuplicateElement(table, new Paragraph(new Run(new Break()
                {
                    Type = BreakValues.Page
                })));
                doc.SaveAs(filepath2).Close();
            }
        }
コード例 #14
0
 public static void CargarContenidoListboxs(string rutaBancoPreguntas)
 {
     BloqueCuestionario = new BloqueCuestionario();
     ListaBloqueCuestionario.Clear();
     try
     {
         using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(rutaBancoPreguntas))
         {
             var body              = document.MainDocumentPart.Document.Body;
             var parrafos          = body.Elements <Paragraph>();
             var listaXTipoDeNivel = ObtenerListaXTipoDeNivel(parrafos);
             ListaBloqueCuestionario = ObtenerListaBloqueCuestionario(listaXTipoDeNivel);
         }
     }
     catch (System.IO.FileNotFoundException)
     {
         Mensajes.ArchivoDeWordNoExiste();
     }
 }
コード例 #15
0
ファイル: Program.cs プロジェクト: Gaurav300/OpenXMLDemo
        static void Main(string[] args)
        {
            const string templatePath = @"C:\Users\Gaurav Koli\source\repos\openXmlDemo\openXmlDemo\target\SampleDocOriginal.docx";
            const string resultPath   = @"C:\Users\Gaurav Koli\source\repos\openXmlDemo\openXmlDemo\Result\result.docx";

            try
            {
                using (WordprocessingDocument wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, true))
                {
                    ReplaceParagraphParts(wordDocument.MainDocumentPart.Document, wordDocument);

                    wordDocument.SaveAs(resultPath);
                }
            }
            catch (IOException ioe)
            {
                Console.WriteLine(ioe.Message);
                Console.ReadKey();
            }
        }
コード例 #16
0
ファイル: Form1.cs プロジェクト: oscarandresdav/TestCreator
 private void CargarContenidoListboxs()
 {
     InicializarListBoxs();
     InicializarLists();
     try
     {
         using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(rutaBancoPreguntas))
         {
             var body     = document.MainDocumentPart.Document.Body;
             var parrafos = body.Elements <Paragraph>();
             var listaContenidoGeneralDePreguntas = ContenidoGeneralDePreguntas(parrafos); // Get a List of Question blocks
                                                                                           //bloqueGeneral = blocks.ConvertAll<List<OpenXmlElement>>(g => g.ConvertAll<OpenXmlElement>(p => (OpenXmlElement)p.CloneNode(true))); // Deep Clone
             listaBloqueCuestionario = ClasificacionNivelPreguntas(listaContenidoGeneralDePreguntas);
             OptimizarListaBloqueCuestionario();
             GetListaClasificacion();
         }
     }
     catch (System.IO.FileNotFoundException)
     {
         Mensajes.ArchivoDeWordNoExiste();
     }
 }
コード例 #17
0
        public void ReplaceProperties(string sourceDocPath, string targetDocPath, Dictionary <string, string> bookmarks)
        {
            //using (WordprocessingDocument doc = WordprocessingDocument.Open(sourceDocPath, true))
            var isEditable = true;

            using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(sourceDocPath, isEditable))
            {
                var body = doc.MainDocumentPart.Document.Body;

                foreach (var paragraph in body.Descendants <Paragraph>())
                {
                    Debug.WriteLine(paragraph);

                    /*if (paragraph.Text.Contains("##sagsid##"))
                     * {
                     *  text.Text = text.Text.Replace("##sagsid##", "Sagsid: 199");
                     * }*/
                }

                foreach (var text in body.Descendants <Text>())
                {
                    if (text.Text.Contains("##sagsid##"))
                    {
                        text.Text = text.Text.Replace("##sagsid##", "Sagsid: 199");
                    }
                }

                foreach (var customProp in doc.CustomFilePropertiesPart.Properties.Descendants <CustomDocumentProperty>())
                {
                    Debug.WriteLine($"Name={customProp.Name} Value={customProp.InnerText}");
                    //customProp.SetAttribute(customProp);
                    //customProp = 173;
                }

                //doc.Save();
                doc.SaveAs(targetDocPath);
            }
        }
コード例 #18
0
        /// <summary>
        /// Creates a SpreadSheetDocument from the specified
        /// template
        /// </summary>
        /// <param name="template">Template url</param>
        /// <returns>WordprocessingDocument reference</returns>
        public static WordprocessingDocument WordDocument(string template = null)
        {
            template = template ?? $@"{AppDomain.CurrentDomain.BaseDirectory}Extensions\Word\Templates\Document.docx";
            if (!template.IsFilePath(out Uri path))
            {
                return(null);
            }
            //Initialize via report template
            WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(template);

            //Compress using maximum value possible
            document.CompressionOption = CompressionOption.Maximum;
            //Bond the body of the document or else create a new one
            Body body = document.MainDocumentPart.Document.Body;

            //Add Document properties
            document.SetProperties(@"Documento");
            //Add extended Document properties
            document.SetExtendedProperties(null, null);
            //Save all changes
            document.Save();
            return(document);
        }
コード例 #19
0
        public static MemoryStream GetWordDocumentFromTemplateWithTempFile()
        {
            string tempFileName = Path.GetTempFileName();
            var    templatePath = AppDomain.CurrentDomain.BaseDirectory + @"Controllers\" + templateFileName;

            using (var document = WordprocessingDocument.CreateFromTemplate(templatePath))
            {
                var body = document.MainDocumentPart.Document.Body;

                //add some text
                Paragraph paraHeader = body.AppendChild(new Paragraph());
                Run       run        = paraHeader.AppendChild(new Run());
                run.AppendChild(new Text("This is body text"));

                OpenXmlPackage savedDoc = document.SaveAs(tempFileName); // Save result document, not modifying the template
                savedDoc.Close();                                        // can't read if it's open
                document.Close();
            }

            var memoryStream = new MemoryStream(File.ReadAllBytes(tempFileName)); // this works but I want to avoid saving and reading file

            //memoryStream.Position = 0; // should I rewind it?
            return(memoryStream);
        }
コード例 #20
0
        public void Export(string targetPath)
        {
            using (this.m_Document = WordprocessingDocument.CreateFromTemplate(this.TemplatePath))
            {
                var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().UseGridTables().UsePipeTables().Build();
                var markdown = Markdown.Parse(this.Source, pipeline);

                foreach (Block block in markdown)
                {
                    if (block is HeadingBlock)
                    {
                        HeadingBlock b = block as HeadingBlock;
                        string       s = "";
                        foreach (Inline run in b.Inline)
                        {
                            s += this.Source.Substring(run.Span.Start, run.Span.Length);
                        }

                        this.m_Document.MainDocumentPart.Document.Body.Append(this.MakeHeaderParagprah(s.ToString(), b.Level));
                    }

                    if (block is ParagraphBlock)
                    {
                        this.m_Document.MainDocumentPart.Document.Body.Append(this.ParseParagaph(block as ParagraphBlock));
                    }

                    if (block is ListBlock)
                    {
                        this.m_Document.MainDocumentPart.Document.Body.Append(this.ParseList(block as ListBlock));
                    }

                    if (block is Markdig.Extensions.Tables.Table)
                    {
                        //TODO Header row

                        Markdig.Extensions.Tables.Table b = block as Markdig.Extensions.Tables.Table;
                        Table table = this.MakeTable();

                        foreach (Block rowBlock in b)
                        {
                            Markdig.Extensions.Tables.TableRow mdRow = rowBlock as Markdig.Extensions.Tables.TableRow;
                            TableRow row = this.MakeTableRow();

                            foreach (Block cellBlock in mdRow)
                            {
                                Markdig.Extensions.Tables.TableCell mdCell = cellBlock as Markdig.Extensions.Tables.TableCell;
                                TableCell cell = this.MakTableCell();

                                foreach (Block content in mdCell)
                                {
                                    if (content is ParagraphBlock)
                                    {
                                        cell.Append(this.ParseParagaph(content as ParagraphBlock));
                                    }
                                }
                                if (mdCell.Count == 0)
                                {
                                    cell.Append(this.MakeParagraph());
                                }
                                row.Append(cell);
                            }
                            table.Append(row);
                        }

                        this.m_Document.MainDocumentPart.Document.Body.Append(table);
                    }

                    if (block is BlockQuote)
                    {
                    }

                    if (block is CodeBlock)
                    {
                    }
                }

                this.m_Document.PackageProperties.Creator     = this.DocumentInfo.First(di => di.Name == "Creator").Value;
                this.m_Document.PackageProperties.Category    = this.DocumentInfo.First(di => di.Name == "Category").Value;
                this.m_Document.PackageProperties.Description = this.DocumentInfo.First(di => di.Name == "Description").Value;
                this.m_Document.PackageProperties.Subject     = this.DocumentInfo.First(di => di.Name == "Subject").Value;
                this.m_Document.PackageProperties.Title       = this.DocumentInfo.First(di => di.Name == "Title").Value;

                //// Save changes to the main document part.
                this.m_Document.MainDocumentPart.Document.Save();

                var doc2 = this.m_Document.SaveAs(targetPath) as WordprocessingDocument;

                doc2.MainDocumentPart.DocumentSettingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(new UpdateFieldsOnOpen()
                {
                    Val = new OnOffValue(true)
                });
                doc2.MainDocumentPart.DocumentSettingsPart.Settings.Save();

                this.m_Document.Close();
                doc2.Close();
            }
        }
コード例 #21
0
        public override void Write()
        {
            ExportFileName = PopulatedName(ExportFileName);
            if (!String.IsNullOrWhiteSpace(ExportFileName))
            {
                DocProperties["FileName"]   = ExportFileName;
                DocProperties["TableCount"] = _dataSet.Tables.Count.ToString();
                if (PopulatePropertiesOnly)
                {
                    if (_dataSet != null)
                    {
                        foreach (DataTable dTable in _dataSet.Tables)
                        {
                            if (dTable.Rows.Count > 0)
                            {
                                foreach (DataColumn dColumn in dTable.Columns)
                                {
                                    DocProperties[dColumn.ColumnName] = dTable.Rows[0][dColumn].ToString();
                                }
                            }
                        }
                    }
                }
                switch (DestinationType)
                {
                case OfficeFileType.WordDocument:
                    WordprocessingDocument doc;
                    if (File.Exists(TemplateFileName))
                    {
                        doc = WordprocessingDocument.CreateFromTemplate(TemplateFileName);
                        doc = (WordprocessingDocument)doc.SaveAs(ExportFileName);
                    }
                    else
                    {
                        doc = WordprocessingDocument.Create(ExportFileName, WordprocessingDocumentType.Document);
                    }
                    CustomFilePropertiesPart customProp = doc.CustomFilePropertiesPart;
                    if (customProp == null)
                    {
                        customProp = doc.AddCustomFilePropertiesPart();
                    }
                    SetFileProperties(customProp);

                    MainDocumentPart mainDoc = doc.MainDocumentPart;
                    if (mainDoc == null)
                    {
                        mainDoc = doc.AddMainDocumentPart();
                    }

                    DocumentSettingsPart settingsPart = mainDoc.GetPartsOfType <DocumentSettingsPart>().First();
                    UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen
                    {
                        Val = new OnOffValue(true)
                    };
                    settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
                    settingsPart.Settings.Save();

                    if (!PopulatePropertiesOnly)
                    {
                        if (mainDoc.Document == null)
                        {
                            mainDoc.Document = new word.Document();
                        }
                        word.Body body       = new word.Body();
                        bool      firstTable = true;
                        foreach (DataTable dt in _dataSet.Tables)
                        {
                            if (!firstTable)
                            {
                                body.Append(GetPageBreak());
                            }
                            else
                            {
                                firstTable = false;
                            }
                            body.Append(GetParagraph(dt.TableName));
                            body.Append(GetWordTable(dt));
                        }
                        mainDoc.Document.Append(body);
                    }
                    mainDoc.Document.Save();
                    doc.Dispose();
                    break;

                case OfficeFileType.ExcelWorkbook:
                    SpreadsheetDocument spreadSheet;
                    if (File.Exists(TemplateFileName))
                    {
                        spreadSheet = SpreadsheetDocument.CreateFromTemplate(TemplateFileName);
                        spreadSheet = (SpreadsheetDocument)spreadSheet.SaveAs(ExportFileName);
                    }
                    else
                    {
                        spreadSheet = SpreadsheetDocument.Create(ExportFileName, SpreadsheetDocumentType.Workbook);
                        spreadSheet.Save();
                    }
                    using (SpreadsheetDocument workbook = spreadSheet)
                    {
                        CustomFilePropertiesPart excelCustomProp = workbook.AddCustomFilePropertiesPart();
                        SetFileProperties(excelCustomProp);

                        if (workbook.WorkbookPart == null)
                        {
                            workbook.AddWorkbookPart();
                        }
                        if (workbook.WorkbookPart.Workbook == null)
                        {
                            workbook.WorkbookPart.Workbook = new excel.Workbook();
                        }
                        if (workbook.WorkbookPart.Workbook.Sheets == null)
                        {
                            workbook.WorkbookPart.Workbook.Sheets = new excel.Sheets();
                        }
                        excel.Sheets sheets = workbook.WorkbookPart.Workbook.Sheets;
                        foreach (DataTable table in _dataSet.Tables)
                        {
                            excel.SheetData sheetData = null;
                            WorksheetPart   sheetPart = null;
                            excel.Sheet     sheet     = null;
                            foreach (OpenXmlElement element in sheets.Elements())
                            {
                                if (element is Sheet)
                                {
                                    sheet = (Sheet)element;
                                    if (sheet.Name.Value.Equals(table.TableName, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        //Assign the sheetPart
                                        sheetPart = (WorksheetPart)workbook.WorkbookPart.GetPartById(sheet.Id.Value);
                                        sheetData = sheetPart.Worksheet.GetFirstChild <SheetData>();
                                        break;
                                    }
                                }
                                sheet = null;
                            }

                            if (sheet == null)
                            {
                                sheetPart           = workbook.WorkbookPart.AddNewPart <WorksheetPart>(); //Create a new WorksheetPart
                                sheetData           = new excel.SheetData();                              //create a new SheetData
                                sheetPart.Worksheet = new excel.Worksheet(sheetData);                     /// Create a new Worksheet with the sheetData and link it to the sheetPart...

                                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);     //get the ID of the sheetPart.
                                sheet = new excel.Sheet()
                                {
                                    Id = relationshipId, SheetId = 1, Name = table.TableName
                                };                        //create a new sheet
                                sheets.Append(sheet);     //append the sheet to the sheets.
                            }

                            List <String> columns = new List <string>();
                            foreach (System.Data.DataColumn column in table.Columns)
                            {
                                columns.Add(column.ColumnName);
                            }
                            if (PrintTableHeader)
                            {
                                excel.Row headerRow = new excel.Row();

                                foreach (string column in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(GetColumnName(table.Columns[column]))
                                    };
                                    headerRow.AppendChild(cell);
                                }


                                sheetData.AppendChild(headerRow);
                            }

                            foreach (DataRow dsrow in table.Rows)
                            {
                                excel.Row newRow = new excel.Row();
                                foreach (String col in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(dsrow[col].ToString())     //
                                    };
                                    newRow.AppendChild(cell);
                                }

                                sheetData.AppendChild(newRow);
                            }
                            sheetPart.Worksheet.Save();
                        }
                        workbook.WorkbookPart.Workbook.Save();
                        workbook.Save();
                        workbook.Close();
                    }

                    break;
                }
            }
        }