Sudha Marothu
Using OpenXML how do we copy data from .csv file to existing excel
ziping parts error
Hi,
I created a presentationml from scratch using xmldocument. ( I am emulating it from Matlab, that is why it is somehow simpler than openxml SDK).
I used "ZipFile.CreateFromDirectory" to package all the files and folder. I can start the document by double clicking on it and it works.
But trying PresentationDocument.Open('newdoc.pptx'). I get the error "missing part". I therefore cannot us "validate".
What is weird to me, is that if I do not use "CreatFromDirectory" and that I pass the all the document manually to a manually precreated zipfile, then change the "zip" to "pptx" the PresentationDocument.Open works!
Anyone wo could help me who knows what should be used to zip all the files together that would mimic the manual process?
Thank you,
Need to convert PPT/PPTX file to PDF using Open XML
Hi All,
I am facing a problem. The scenario is : I need to convert PPT/PPTX file to PDF file using Open XML without dependency of Open Office & MS Office (I cant take help of "Microsoft.Office.Interop"). This needs to be done by C# code without installation any purchased/free third party software. This will be simple Windows programming (With C# only) . I am using Visual Studio 2010 & the development must be in that version of VS. In my machine MS Office & Open Office is not installed.
Can any one please provide me any sample code or any link which can be fruitful for me?
Any help will appreciate and thanks in advance.
Manipulating Word Docs using OpenXML
I have a few MS Word documents I am attempting to manipulate via OpenXML 2.0 but having some difficulty. I am hoping someone can assist w/ some the issues listed below:
1. The MS Word documents are created from Word template files (.dotx). However, I am receiving the following error after creating the doc from the template:
Error message: "The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'."
XPath - "/w:settings[1]"
The code in creating a document from the template is as follows:
If File.Exists(sFile.Replace("dotx", "docx")) Then Delete(sFile.Replace("dotx", "docx")) File.Copy(sFile, sFile.Replace("dotx", "docx")) 'create word doc moWordDoc = WordprocessingDocument.Open(sFile.Replace("dotx", "docx"), True) 'change doc type, which ensures the document is no longer marked as a Template but rather as a Document moWordDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document) oAttachedTemplate = New AttachedTemplate oAttachedTemplate.Id = "relationId1" 'append the AttachedTemplate to the DocumentSettingsPart oMainPart = moWordDoc.MainDocumentPart oDocSettings = oMainPart.DocumentSettingsPart oDocSettings.Settings.Append(oAttachedTemplate) oDocSettings.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", _ New Uri(sFile, UriKind.Absolute), "relationId1")
I've also tried creating the document w/out attaching the template file to the doc but the document will open in MS Word w/ empty data.
2. A couple of the Word templates contain various background images in the tables of the template. The images act as background colors for the tables are and OpenXML doesn't seem to like. The following error is returned when validating the document:
Error message: The 'urn:schemas-microsoft-com:office:office:gfxdata' attribute is not declared.
XPath - "/w:document[1]/w:body[1]/w:tbl[1]/w:tr[1]/w:tc[1]/w:p[1]/w:r[2]/w:pict[1]/v:rect[1]"
3. Lastly, in each of the Word templates, OpenXML doesn't seem to be processing the first cell in the first row of the first table in the template. Each template contains a bookmark in the first row and cell of the table. The error returned is as follows:
Error message - "The element has invalid child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:r'."
XPath - "/w:document[1]/w:body[1]/w:tbl[1]"
The Run statement appears to be ok and is used throughout the document to fill bookmarks. Here's a sample of the code:
If m_arrBookmarkStarts.ContainsKey("client_name") Then oBookmarkStart = m_arrBookmarkStarts("client_name") id = oBookmarkStart.Id.Value oBookmarkEnd = m_arrBookmarkEnds(id) oText = New Text(moInvoice.Client_fname & " " & moInvoice.Client_lname) oElement = New Run(oText) oBookmarkStart = RemoveBookmarkText(oBookmarkStart, oBookmarkEnd) End If Private Function RemoveBookmarkText(ByVal oBookmarkStart As BookmarkStart, ByVal oBookmarkEnd As BookmarkEnd) Dim oElement As DocumentFormat.OpenXml.OpenXmlElement Dim oNextElem As DocumentFormat.OpenXml.OpenXmlElement If Not IsNothing(oBookmarkStart.ColumnFirst) Then Return oBookmarkStart oElement = oBookmarkStart.NextSibling While (Not IsNothing(oElement) And Not oElement Is oBookmarkEnd) oElement.Remove() oNextElem = oElement.NextSibling oElement = oNextElem End While 'clean up oElement = Nothing oNextElem = Nothing Return oBookmarkStart End Function
Any help is appreciated
jim
Manipulating Word Docs using OpenXML
Hello,
I have a few MS Word documents I am attempting to manipulate via OpenXML 2.0 but having some difficulty. I am hoping someone can assist w/ some the issues listed below:
1. The MS Word documents are created from Word template files (.dotx). However, I am receiving the following error after creating the doc from the template:
Error message: "The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'."
XPath - "/w:settings[1]"
The code in creating a document from the template is as follows:
If File.Exists(sFile.Replace("dotx", "docx")) Then File.Delete(sFile.Replace("dotx", "docx")) File.Copy(sFile, sFile.Replace("dotx", "docx")) 'create word doc moWordDoc = WordprocessingDocument.Open(sFile.Replace("dotx", "docx"), True) 'change doc type, which ensures the document is no longer marked as a Template but rather as a Document moWordDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document) oAttachedTemplate = New AttachedTemplate oAttachedTemplate.Id = "relationId1" 'append the AttachedTemplate to the DocumentSettingsPart oMainPart = moWordDoc.MainDocumentPart oDocSettings = oMainPart.DocumentSettingsPart oDocSettings.Settings.Append(oAttachedTemplate) oDocSettings.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", _ New Uri(sFile, UriKind.Absolute), "relationId1")
I've also tried creating the document w/out attaching the template file to the doc but the document will open in MS Word w/ empty data.
2. A couple of the Word templates contain various background images in the tables of the template. The images act as background colors for the tables are and OpenXML doesn't seem to like. The following error is returned when validating the document:
Error message: The 'urn:schemas-microsoft-com:office:office:gfxdata' attribute is not declared.
XPath - "/w:document[1]/w:body[1]/w:tbl[1]/w:tr[1]/w:tc[1]/w:p[1]/w:r[2]/w:pict[1]/v:rect[1]"
3. Lastly, in each of the Word templates, OpenXML doesn't seem to be processing the first cell in the first row of the first table in the template. Each template contains a bookmark in the first row and cell of the table. The error returned is as follows:
Error message - "The element has invalid child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:r'."
XPath - "/w:document[1]/w:body[1]/w:tbl[1]"
The Run statement appears to be ok and is used throughout the document to fill bookmarks. Here's a sample of the code:
If m_arrBookmarkStarts.ContainsKey("client_name") Then oBookmarkStart = m_arrBookmarkStarts("client_name") id = oBookmarkStart.Id.Value oBookmarkEnd = m_arrBookmarkEnds(id) oText = New Text(moInvoice.Client_fname & " " & moInvoice.Client_lname) oElement = New Run(oText) oBookmarkStart = RemoveBookmarkText(oBookmarkStart, oBookmarkEnd) End If Private Function RemoveBookmarkText(ByVal oBookmarkStart As BookmarkStart, ByVal oBookmarkEnd As BookmarkEnd) Dim oElement As DocumentFormat.OpenXml.OpenXmlElement Dim oNextElem As DocumentFormat.OpenXml.OpenXmlElement If Not IsNothing(oBookmarkStart.ColumnFirst) Then Return oBookmarkStart oElement = oBookmarkStart.NextSibling While (Not IsNothing(oElement) And Not oElement Is oBookmarkEnd) oElement.Remove() oNextElem = oElement.NextSibling oElement = oNextElem End While 'clean up oElement = Nothing oNextElem = Nothing Return oBookmarkStart End Function
Any help is appreciated
jim
Why does the word doc show up with the wrong font And bold?
Ive been using the sdk productivity tool to extract the code that builds the document structure; but now the table is coming out with the wrong font and style, its not what was there in the original, and its not clear in the code where its getting this wrong font from?
It should be timesnew roman, 12pt, standard. it comes out 14pt BOLD and the headers of the table are 18pt bold. they are set as 14pt bold. i notice the style of "no spacing" in there, but is it using this?
the fontsize {val = "24"} tells me its font 12pt because its 1/2 of the number?
Run run6 = new Run(); RunProperties runProperties6 = new RunProperties(); RunFonts runFonts12 = new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; FontSize fontSize12 = new FontSize() { Val = "24" }; FontSizeComplexScript fontSizeComplexScript12 = new FontSizeComplexScript() { Val = "24" }; runProperties6.Append(runFonts12); runProperties6.Append(fontSize12); runProperties6.Append(fontSizeComplexScript12); Text text6 = new Text(); text6.Text = "PZ1"; run6.Append(runProperties6); run6.Append(text6); paragraph7.Append(paragraphProperties7); paragraph7.Append(run6); tableCell6.Append(tableCellProperties6); tableCell6.Append(paragraph7); TableCell tableCell7 = new TableCell(); TableCellProperties tableCellProperties7 = new TableCellProperties(); TableCellWidth tableCellWidth7 = new TableCellWidth() { Width = "1530", Type = TableWidthUnitValues.Dxa }; TableCellVerticalAlignment tableCellVerticalAlignment2 = new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }; tableCellProperties7.Append(tableCellWidth7); tableCellProperties7.Append(tableCellVerticalAlignment2); Paragraph paragraph8 = new Paragraph() { RsidParagraphMarkRevision = "00881B22", RsidParagraphAddition = "00881B22", RsidParagraphProperties = "00881B22", RsidRunAdditionDefault = "00C12F2C" }; ParagraphProperties paragraphProperties8 = new ParagraphProperties(); ParagraphStyleId paragraphStyleId8 = new ParagraphStyleId() { Val = "NoSpacing" }; ParagraphMarkRunProperties paragraphMarkRunProperties7 = new ParagraphMarkRunProperties(); RunFonts runFonts13 = new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; FontSize fontSize13 = new FontSize() { Val = "24" }; FontSizeComplexScript fontSizeComplexScript13 = new FontSizeComplexScript() { Val = "24" }; paragraphMarkRunProperties7.Append(runFonts13); paragraphMarkRunProperties7.Append(fontSize13); paragraphMarkRunProperties7.Append(fontSizeComplexScript13); paragraphProperties8.Append(paragraphStyleId8); paragraphProperties8.Append(paragraphMarkRunProperties7);
Display image in word document bookmark using Open XML [SDK 2.0] and C# code.
Hi,
I need to implement word document generation using Open XML [SDK 2.0] and C# code.
I have Word document template .docx file with number of Bookmarks. I need to insert an image at a specified Bookmark (or can be between two bookmarks - ImageStart/ImageEnd). Please assist with the relevant C# code.
In addition, the image is stored in an SQL table [column datatype - Image], hence the code should be able to pull the image from SQL table and display in the Word document at the specified bookmark.
Thanks & Regards,
Gladson Bayer
How to add Notes to a pirticular slide in a ppt?
Currently I have a task that insert custom note to a particular slide of a ppt using openxml. from referencing this "https://msdn.microsoft.com/en-us/library/office/gg278319.aspx" . I am trying to add note to a slide but I am getting the following Error.
Error Message :Only one instance of the type is allowed for this parent.
Stack Trace:
at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.InitPart[T](T newPart, String contentType, String id) at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.InitPart[T](T newPart, String contentType) at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.AddNewPartInternal[T]() at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.AddNewPart[T]() at AddNoteToPPT.Program.AddNote(String docName, Int32 index) in d:\Projects\Task\Project\AddNoteToPPT\AddNoteToPPT\Program.cs:line 45
Here is my working copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml;
using P = DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Drawing;
namespace AddNoteToPPT
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\Projects\Task\Documents\OpenXML.pptx";
AddNote(filePath, 0);
}
public static void AddNote(string docName, int index)
{
using (PresentationDocument ppt = PresentationDocument.Open(docName, true))
{
// Get the relationship ID of the first slide.
PresentationPart part = ppt.PresentationPart;
OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements;
string relId = (slideIds[index] as SlideId).RelationshipId;
// Get the slide part from the relationship ID.
SlidePart slide = (SlidePart)part.GetPartById(relId);
// Build a StringBuilder object.
StringBuilder paragraphText = new StringBuilder();
// Get the inner text of the slide:
IEnumerable<A.Text> texts = slide.Slide.Descendants<A.Text>();
NotesSlidePart notesSlidePart1 = slide.AddNewPart<NotesSlidePart>();
NotesSlide notesSlide = new NotesSlide(
new CommonSlideData(new ShapeTree(
new P.NonVisualGroupShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()),
new GroupShapeProperties(new TransformGroup()),
new P.Shape(
new P.NonVisualShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" },
new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape())),
new P.ShapeProperties(),
new P.TextBody(
new BodyProperties(),
new ListStyle(),
new Paragraph(new EndParagraphRunProperties()))))),
new ColorMapOverride(new MasterColorMapping()));
notesSlidePart1.NotesSlide = notesSlide;
}
}
}
}
using this code I am able to get the content of existing Note.
slide.NotesSlidePart.SlidePart.NotesSlidePart.NotesSlide.InnerText
Print GridLines
How can I set and apply the PrintOptions for Spreadsheet to print the Gridlines?
The msn documentation doesn't really tell you how, and I couldn't find a sample either.
This is what I got, but this creates an error: (the Excel file can't be opened)
If I take out the SetPrintOptions, everything else works as should.
using (var spreadSheet = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = spreadSheet.AddWorkbookPart();
WorksheetPart workSheetPart = workbookPart.AddNewPart<WorksheetPart>();
Workbook workbook = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet workSheet = new Worksheet();
SheetData sheetData = new SheetData();
//workSheetPart.Worksheet = new Worksheet(sheetData);
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = StylesheetUtility.GenerateStyleSheet();
stylesPart.Stylesheet.Save();
List<int[]> subTables = new List<int[]>();
int rowNum = ProcessDataGrid(workSheet, sheetData, dg, ExcludeColumnHeaders, 1, true, ExcludeSubColumnHeaders, onlyInner, true, subTables, workSheetPart, imageColumns,
isImageSameColumn);
workSheet.Append(sheetData);
SetSheetPrintProperties(workSheet, 1, 1, OrientationValues.Landscape);
//set Printer Options Gridlines
workSheet.Append(SetPrintOptions(true));
workSheetPart.Worksheet = workSheet;
workSheetPart.Worksheet.Save();
Sheets sheets = workbook.GetFirstChild<Sheets>();
if (sheets == null) sheets = new Sheets();
string relationshipId = workbookPart.GetIdOfPart(workSheetPart);
uint sheetId = (sheets.Elements<Sheet>().Count() > 0) ? sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1 : 1;
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = name };
sheets.Append(sheet);
workbook.Append(fv);
workbook.Append(sheets);
spreadSheet.WorkbookPart.Workbook = workbook;
spreadSheet.WorkbookPart.Workbook.Save();
}
public void SetSheetPrintProperties(Worksheet ws, UInt32 fitToHeight, UInt32 fitToWidth, OrientationValues orient = OrientationValues.Portrait)
{
SheetProperties sp = new SheetProperties(new PageSetupProperties());
ws.SheetProperties = sp;
// Set the FitToPage property to true
ws.SheetProperties.PageSetupProperties.FitToPage = BooleanValue.FromBoolean(true);
DocumentFormat.OpenXml.Spreadsheet.PageSetup pgOr = new DocumentFormat.OpenXml.Spreadsheet.PageSetup();
pgOr.Orientation = DocumentFormat.OpenXml.Spreadsheet.OrientationValues.Landscape;
pgOr.FitToHeight = fitToHeight;
pgOr.FitToWidth = fitToWidth;
ws.AppendChild(pgOr);
}
private PrintOptions SetPrintOptions(bool printGridLines)
{
PrintOptions po = new PrintOptions();
po.GridLines = true;
po.GridLinesSet = true;
return po;
}
Adding c:strRef and c:numRef nodes
Am dynamically creating a chart in Excel. Generated excel file misses the (c:strRef and c:numRef nodes), making chart unable to get imported to some Powerpoint slide.
Help needed to generate the above missing nodes through code for any specific chart. Thanks, in advance.
Thanks,
Imtiaz Qamar
OpenXmlSdkTool crashes on startup
I cannot start Microsoft office open XML SDK 2.0.
When ever i start 'Open XML SDK 2.0 Productivity Tool' if crash display the error reporting screen.
It has never worked.
has anybody had this problem and how did you fix it (if you ever did get it fixed !)
Word Protection Feature (Forms) in OpenXml
We need the ability to have some fields in a form set to read only where others can be edited by the end user.
The rest of the document would need to be read only, and the ability to save/print the result will also be necessary.
Is there a way to get this done using the DocumentProtection or FormProtection objects in the OpenXML SDK?
Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
hi,
am getting this error(Cannot insert the OpenXmlElement "newChild" because it is part of a tree.) when i try to give border values to the table.
here is my code,
if
(sValue ==""){
InsideVerticalBorder insideVBorder =newInsideVerticalBorder();
insideVBorder.Val =
newEnumValue<BorderValues>(BorderValues.None);tblBorders.AppendChild(insideVBorder);
}
else
{
InsideVerticalBorder insideVBorder =newInsideVerticalBorder();
insideVBorder.Val =
newEnumValue<BorderValues>(BorderValues.Single);tblBorders.AppendChild(insideVBorder);
}
banupriya
Write Rich text contents to a word document
Hello,
I have a requirement to write formatted text to a Word document. User can enter text and it has to be inserted into an existing word document. Formatting of the text should be retained. I'm using rich text box for the user input.
Is there a way where the RTF contents can be written to a word document using OpenXML?
Thanks for the help
Praneeth
How to allow the content of a Word doc, created using OpenXml, to be editable (using Word).
Hi.
I have successfully used OpenXml (2.5) to use a Word Template and live SQL data to create an Invoice.
I would like to be able to edit the contents of this invoice that have been dynamically generated by the process in the resulting Word document.
How would I go about doing this?
Here's the C#:
// Make a copy of the template file string templatePath = Server.MapPath("/admin/exports/templates/"); string generatedPath = Server.MapPath("/admin/exports/"); File.Copy(templatePath + "Quote_Template.docx", generatedPath + "Quote_" + chooseQuoteDropDownList.SelectedItem.Text + ".docx", true); //Open, populate and save the copied template word doc using (WordprocessingDocument theDoc = WordprocessingDocument.Open(generatedPath + "Quote_" + chooseQuoteDropDownList.SelectedItem.Text + ".docx", true)) { //Connect to database string connectionString = WebConfigurationManager.ConnectionStrings["*****"].ConnectionString; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); // Open the doc MainDocumentPart mainPart = theDoc.MainDocumentPart; // Insert quote reference number: // taken simply from the SelectedValue of the initial DDL. SdtElement inline_01 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "quoteRef").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t2 = inline_01.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t2.Text = chooseQuoteDropDownList.SelectedItem.Text; // Insert recipient's email address: // taken from database string commandString1 = "SELECT Email FROM aspnet_Membership INNER JOIN orders ON aspnet_Membership.UserId = orders.customer_id WHERE order_id = @order_id"; SqlCommand cmd1; cmd1 = new SqlCommand(commandString1, conn); cmd1.Parameters.AddWithValue("@order_id", chooseQuoteDropDownList.SelectedValue); string mailAddress = Convert.ToString(cmd1.ExecuteScalar()); SdtElement inline_02 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "recipientEmail").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t3 = inline_02.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t3.Text = mailAddress; // Insert recipient's name: // taken from database string commandString2 = "SELECT firstname + ' ' + lastname as firstlast FROM user_extra_info INNER JOIN orders ON user_extra_info.UserId = orders.customer_id WHERE order_id = @order_id"; SqlCommand cmd2; cmd2 = new SqlCommand(commandString2, conn); cmd2.Parameters.AddWithValue("@order_id", chooseQuoteDropDownList.SelectedValue); string name = Convert.ToString(cmd2.ExecuteScalar()); SdtElement inline_03 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "recipientTo").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t4 = inline_03.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t4.Text = name; // Insert recipient's company: // taken from database string commandString3 = "SELECT companyname FROM user_extra_info INNER JOIN orders ON user_extra_info.UserId = orders.customer_id WHERE order_id = @order_id"; SqlCommand cmd3; cmd3 = new SqlCommand(commandString3, conn); cmd3.Parameters.AddWithValue("@order_id", chooseQuoteDropDownList.SelectedValue); string company = Convert.ToString(cmd3.ExecuteScalar()); SdtElement inline_04 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "recipientCompany").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t5 = inline_04.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t5.Text = company; // Insert recipient's telephone number: // taken from database string commandString4 = "SELECT telephone FROM user_extra_info INNER JOIN orders ON user_extra_info.UserId = orders.customer_id WHERE order_id = @order_id"; SqlCommand cmd4; cmd4 = new SqlCommand(commandString4, conn); cmd4.Parameters.AddWithValue("@order_id", chooseQuoteDropDownList.SelectedValue); string phone = Convert.ToString(cmd4.ExecuteScalar()); SdtElement inline_05 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "recipientPhone").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t6 = inline_05.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t6.Text = phone; // Insert recipient's name after "Dear": // taken from database string commandString5 = "SELECT firstname FROM user_extra_info INNER JOIN orders ON user_extra_info.UserId = orders.customer_id WHERE order_id = @order_id"; SqlCommand cmd5; cmd5 = new SqlCommand(commandString5, conn); cmd5.Parameters.AddWithValue("@order_id", chooseQuoteDropDownList.SelectedValue); string firstname = Convert.ToString(cmd5.ExecuteScalar()); SdtElement inline_06 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "recipientName").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t7 = inline_06.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t7.Text = firstname; // Insert Conversion Rate mid document: // taken from rate calculation at start of event SdtElement inline_07 = mainPart.Document.Body.Descendants<SdtElement>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "convRate").Single(); DocumentFormat.OpenXml.Wordprocessing.Text t8 = inline_07.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(); t8.Text = rateEuro.ToString("0.##"); // Populate the main table SdtBlock ccWithTable = mainPart.Document.Body.Descendants<SdtBlock>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == "tableMain").Single(); // This should return only one table. DocumentFormat.OpenXml.Wordprocessing.Table theTable = ccWithTable.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>().Single(); //Connect to database QuoteExportDataContext db = new QuoteExportDataContext(); var productListing = from admin_product in db.admin_products select new { admin_product.code, admin_product.product_title, admin_product.quantity, admin_product.unit_customer_cost, admin_product.total_customer_cost, admin_product.supplier_list_price }; // Get the last row in the table. DocumentFormat.OpenXml.Wordprocessing.TableRow theRow = theTable.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().Last(); decimal total = 0; decimal total_pd = 0; int counter = 1; foreach (var product in productListing) { DocumentFormat.OpenXml.Wordprocessing.TableRow rowCopy = (DocumentFormat.OpenXml.Wordprocessing.TableRow)theRow.CloneNode(true); // Counter rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(0).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(0).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(counter.ToString() + ")")) ) ); // Product Code rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(1).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(1).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(product.code.ToString())) ) ); // Product Title rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(2).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(2).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(product.product_title.ToString())) ) ); // Quantity rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(3).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(3).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(product.quantity.ToString())) ) ); // Unit Customer Cost rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(4).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(4).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(string.Format("{0:f2}", currencySymbol + "" + (Convert.ToDecimal(product.supplier_list_price) * rate).ToString("#.##")))) ) ); // Total Customer Cost rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(5).RemoveAllChildren(); rowCopy.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().ElementAt(5).Append( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } ), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(string.Format("{0:f2}", currencySymbol + "" + ((Convert.ToDecimal(product.supplier_list_price) * Convert.ToDecimal(product.quantity)) * rate).ToString("#.##")))) ) ); theTable.AppendChild(rowCopy); // Add Total Cost total += (Convert.ToDecimal(product.supplier_list_price) * Convert.ToDecimal(product.quantity)) * rate; total_pd += Convert.ToDecimal(product.total_customer_cost) * rate; counter++; } // Delivery Row int delCharge = Convert.ToInt32(deliveryDropDownList.SelectedValue); DocumentFormat.OpenXml.Wordprocessing.TableRow totalRow_Del = new DocumentFormat.OpenXml.Wordprocessing.TableRow(); DocumentFormat.OpenXml.Wordprocessing.TableCell tc1_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc1_del.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc2_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc2_del.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc3_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc3_del.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc4_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc4_del.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc5_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text("Delivery:") ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc6_del = new DocumentFormat.OpenXml.Wordprocessing.TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(currencySymbol + (string.Format("{0:f2}", delCharge))) ))); totalRow_Del.Append(tc1_del, tc2_del, tc3_del, tc4_del, tc5_del, tc6_del); theTable.AppendChild(totalRow_Del); // Total Row DocumentFormat.OpenXml.Wordprocessing.TableRow totalRow_Tot = new DocumentFormat.OpenXml.Wordprocessing.TableRow(); DocumentFormat.OpenXml.Wordprocessing.TableCell tc1_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc1_tot.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc2_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc2_tot.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc3_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc3_tot.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc4_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell(new Paragraph()); tc4_tot.Append( new TableCellProperties( new TableCellBorders( new DocumentFormat.OpenXml.Wordprocessing.BottomBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder { Val = BorderValues.None, Size = (UInt32Value)1U }, new DocumentFormat.OpenXml.Wordprocessing.TopBorder { Val = BorderValues.None, Size = (UInt32Value)1U } ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc5_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text("TOTAL:") ))); DocumentFormat.OpenXml.Wordprocessing.TableCell tc6_tot = new DocumentFormat.OpenXml.Wordprocessing.TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new DocumentFormat.OpenXml.Wordprocessing.Run( new RunFonts { Ascii = "Palatino Linotype" }, new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.FontSize { Val = "20" }), new DocumentFormat.OpenXml.Wordprocessing.Text(currencySymbol + (string.Format("{0:f2}", total_pd + delCharge))) ))); totalRow_Tot.Append(tc1_tot, tc2_tot, tc3_tot, tc4_tot, tc5_tot, tc6_tot); theTable.AppendChild(totalRow_Tot); // Remove the empty placeholder row from the table. theTable.RemoveChild(theRow); // Save the changes to the table back into the document. mainPart.Document.Save(); }
Thanks in advance.
Do External Images use a GET or a POST
The title says it all. I have an externally linked image in an excel file. Basically I want to know if the request the document makes when loading an external image is a GET or a POST.
Ultimately I'd like to send some data back to the server from which the image is loaded.
If I'm completely off the mark, please let me know.
Thanks for any input!
How to delete Content Control in Word document using OpenXML Format SDK?
Hi,
How to delete Content Control in Word document using OpenXML Format SDK?
Selvam S
How to set different page orientations for even and odd pages using OpenXML?
Is there a way, using Open XML SDK, to set different page orientation for even and odd pages of word document? I want to set landscape orientation for odd number of pages and portrait to even number of pages dynamically using OpenXML in C#.
It will be good if you can provide the sample code for the same.
Thank you.
How to covert Listparagraph to ListFormat.ConvertNumbersToText() using OpenXML Format SDK?
Hi,
I have a word document with number ordered list & bulletin list paragraph.
I want to convert number ordered list & bulletin list as text format.
How can i do ListFormat.ConvertNumbersToText() using OpenXML Format SDK?
Selvam S
identify the smartartshape bounds using the smart art bounds.
Hi ,
In MS PowerPoint i simply adding a smart art of AlternatingHexagon type.
The default position of the smart art will be generated as
Horizontal Position = 2.22
Vertical Position = 0.79
Width = 8.89
Height = 5.93
My Query is,
Inside the AlternatingHexagons type smart art, it consists of 9 autoshapes like hexagons,. If is select the first node(first hexagon) means its default position will be generated as
Horizontal Position = 3.84
Vertical Position = 0.14
Width = 2.2
Height = 1.91
In what basis the above size and position will be calculated ? Further, when i change the entire smart art size, the above bounds changes accordingly. Could you please provide me the formula or algorithm for finding the size and position of the shapes present inside the smart art?
Thanks,
Arun