i have a wordMl of range which i got from interop document using statement below:
string myWordMl = myRange.WordOpenXML
now i have created an openxml document and i want to append myWordMl into the body this openxml document.
i have a wordMl of range which i got from interop document using statement below:
string myWordMl = myRange.WordOpenXML
now i have created an openxml document and i want to append myWordMl into the body this openxml document.
foreach (WeekSummary summary in report.Summary)
{
DocumentFormat.OpenXml.Spreadsheet.Row row = new DocumentFormat.OpenXml.Spreadsheet.Row();
row.RowIndex = (UInt32)rowIndex++;
row.AppendChild<Cell>(new Cell() { DataType = CellValues.String, CellValue = new CellValue(summary.Name ?? "") });
row.AppendChild<Cell>(new Cell() { DataType = CellValues.String, CellValue = new CellValue(summary.Contact ?? "") });
sheetData.AppendChild<Row>(row);
}
This is my code which i've insert cells to row.. I want to lock those cells.. I wouldn't find any solution for this ?
How to resolve this programmatically (c#.net)?
I couldn't find the solution for this?
could you please help me , by giving the code ?
hi,
i would like to read an excel file and read the headers in the excel file and insert the records into sp 2010 splist/doc lib.
is it possible, any sample code is appeciated
thnx
Hello Team,
I have used OpenXml to update a sheet in excel file. I have achieved this by referring the MSDN
http://msdn.microsoft.com/en-us/library/hh180830(v=office.14).aspx
Now i am updating an excel cell with large text separated by '\n'. I need to set theWrap Text to the cell through OpenXMl C#. With out wrap text the string is appearing in one line which is disappointed.
I have tried to add a style sheet through code, i got exception "only one instance can be allowed"
Please provide a solution to give wrap text to a cell in excel using open xml. My code is similar to the MSDN
Any help is appritiated
Thanks & Regards,
Programmer Kadapa
i am inserting a wordMl on my current selection range
here is the wordMl i want to insert
<?mso-application progid="Word.Document"?><pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage"><pkg:part pkg:name="/word/afchunk2.docx" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" /><pkg:part pkg:name="/word/document.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"><pkg:xmlData><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t></w:t></w:r></w:p><w:altChunk r:id="AltChunkId1" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /></w:body></w:document></pkg:xmlData></pkg:part><pkg:part pkg:name="/word/_rels/document.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml"><pkg:xmlData><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk2.docx" Id="AltChunkId1" /></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml"><pkg:xmlData><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/word/document.xml" Id="R1ff464e618a64ac8" /></Relationships></pkg:xmlData></pkg:part></pkg:package>
but when i insert it using
range.insertXml method it throws following exception message
"XML markup cannot be inserted in the specified location."
i have created document using openXml sdk.
I am trying to embed an object into an excel programmatically and encountering an issue. I am using the below code to embed an file into Excel.
EmbeddedObjectPart embeddedObjectPart1 = worksheetPart.AddNewPart<EmbeddedObjectPart>("application/vnd.openxmlformats-officedocument.oleObject","rId4");
embeddedObjectPart1.FeedData(File.Open(filepath,FileMode.Open));
When I try to open the generated Excel, I get the below
"We Found a Problem with some content in 'book1.xlsx'.Do you want us to try to recover as much as we can ...."
When I click on “yes”, the embedded object is removed and only the image of the file is present in the excel.
Are there any additional properties I need to set as part of the embedded object.
Hi,
I have an application that is using OpenXML and AltChunk to insert plain text (from a XML-file) into various Content Controls (I've tried Rich Text and Plain Text controls). Now, this works, kind of. The text gets inserted in the right Content Controls, but the problem is that the font is Courier New - 10,5. The other content in the document (not inserted by the application) isBalibri (Body) 11, which is the document default.
How can I override this in the code?
Do I need to do some sort of encoding on the string I'm inserting?
Here my code:
private void AddAltChunk(MainDocumentPart mainPart, Word.SdtBlock sdt, string stringToInsert) { string altChunkId = "AltChunkId" + _id; _id++; byte[] byteArray = null; // Make bytearray of stringToInsert byteArray = new byte[stringToInsert.Length * sizeof(char)]; byteArray = Encoding.ASCII.GetBytes(stringToInsert); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.TextPlain, altChunkId); using (MemoryStream mem = new MemoryStream()) { mem.Write(byteArray, 0, (int)byteArray.Length); mem.Seek(0, SeekOrigin.Begin); chunk.FeedData(mem); } Word.AltChunk altChunk = new Word.AltChunk(); altChunk.Id = altChunkId; // Replace content control with altChunk information. OpenXmlElement parent = sdt.Parent; parent.InsertAfter(altChunk, sdt); sdt.Remove(); } }Thanks for any help/input!
Hi,
I need to insert images in different pages. All the images will be different and it will be inserted in to different location like table cells.
I have tried the example in the MSDN link -http://msdn.microsoft.com/en-us/library/office/bb497430.aspx
But after inserting the document is getting corrupted. Insertion of one image with the same code works , but i try inserting another image document is getting corrupted. RelationshipID is passed different from addImagePart creates new relationshipID.
I tried opening recovered docuemnt and the corrupted document in Open XMl SDk 2.5 Productivity Tool and i Could see the images are stored in /media/folder in the corrupted document and /word/media/ in the recovered document. Is this would be the reason for getting corrupted?
Pleas help me with this as i'm stuck with this for some time
I'm using OS: Windows 8, OpenXMLSDK 2.5 and office 2013
regards,
Swaroop
i have a wordMl of an
interop.Range
which gives the whole package xml, i want to load it to a new WordProcessingDocument using either of the method
WordProcessingDocument.Open() or WordProcessingDocument.Create()
(note: i have stored interop.Range in a string)
Hi
In our project we are creating documents from a predefined text-document on which we apply headers, footers, margins, themes and styles from a Word template (dotx).
The solution has worked fine as a webservice in every case so far, but we are now experiencing problems regarding table styles.
If the predefined text has a tablestyle set, for instance "Medium dark-shadow1-color 1" (translated from swedish), which also exists in the template and is a part af the standard Office Theme, the document looses the style and the table ends up as plain white one.
We apply styles from the template with the following code:
Friend Sub WDCopyStyles(ByVal fromdoc As String, ByVal toDoc As String) Dim wordDoc1 As WordprocessingDocument = WordprocessingDocument.Open(fromdoc, False) Dim wordDoc2 As WordprocessingDocument = WordprocessingDocument.Open(toDoc, True) Dim styleDefPart = wordDoc1.MainDocumentPart.GetPartsOfType(Of StyleDefinitionsPart).FirstOrDefault() Dim styleDefPart2 = wordDoc2.MainDocumentPart.GetPartsOfType(Of StyleDefinitionsPart).FirstOrDefault() Using wordDoc2 If styleDefPart2 Is Nothing Then wordDoc2.MainDocumentPart.AddPart(Of StyleDefinitionsPart)(styleDefPart) Else wordDoc2.MainDocumentPart.DeletePart(styleDefPart2) wordDoc2.MainDocumentPart.AddPart(Of StyleDefinitionsPart)(styleDefPart) End If End Using wordDoc1.Close() End Sub
What am I missing?
Thanks in advance
Best Regards Peter Karlström Midrange AB, Sweden
Hi Folks,
I have a simple word document that contains content controls (just plain text ones). The issue that I am having is that some of the content controls are embedded in other elements (such as tables) and I am unable to find them in the document.
if I create a simple document that contains a PlainText content control called bob and put it in the root of the document and perform the following:-
List<SdtBlock> blockList = mainDocumentPart.Document.Decendants<SdtBlock>().ToList()
I get one element returned which I can examine blockList[0].SdtProperties.GetFirstChild<Tag>() and I get a valid tag element back.
However, if I then add a table, then put another control inside called 'fred', block list will contain 2 elements, but the second element will not contain a tag property.
The fred block is nested several levels deep and I am looking for a way to find it (regardless of what it is nested in) so that I can update its contents?
Does anyone have a working way to do this
Hi,
I am using Open XML SDK 2.5 and C# 4.0. I need to extract the VBA code from a macro enabled Excel file.
I could not find any classes in their documentation. I tried the Productivity Tool to view the VBA source code, but it shows only the binary code for the VBA part.
Is it possible to extract the VBA source code using the Open XML SDK?
I appreciate any help or direction.
Thanks
- Jaideep
jd
Hi,
I am using Office Interop to convert powerpoint to pdf using save as functionality with below code. I have some issues with InterOp on some pcs where I get application is busy error.
Is it possible to convert .pptx to .pdf using open xml sdk? if yese, please provide me some sample.
public static void ConvertPPTtoPDF(string pptFile, string pdfFile)
{
try
{
Microsoft.Office.Interop.PowerPoint.Application ppApp = new
Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Presentation presentation = ppApp.Presentations.Open
(pptFile, Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoFalse);
presentation.ExportAsFixedFormat(pdfFile,
PPT.PpFixedFormatType.ppFixedFormatTypePDF,
PPT.PpFixedFormatIntent.ppFixedFormatIntentPrint,
Microsoft.Office.Core.MsoTriState.msoFalse,
PPT.PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst,
PPT.PpPrintOutputType.ppPrintOutputSlides,
Microsoft.Office.Core.MsoTriState.msoFalse,
null,
PPT.PpPrintRangeType.ppPrintAll,
"",
false,
false,
false,
true,
true,
System.Reflection.Missing.Value);
presentation.Close();
presentation = null;
ppApp = null;
GC.Collect();
}
catch (Exception ex)
{
Console.WriteLine("exception happened while converting to PDF file..." + ex);
throw ex;
}
}
VM7258
Hi,
I have been trying to achieve a seemingly simple task of adding a header and an image inside it but i can't seem to do it. I have tried several examples but none seem to work (even the ones on MSDN). It appears to be a problem with properly referencing the image part within the xml. Whenever i add an image, the document doesn't open in Word anymore. Can someone please shed some light on this with an actual working example?
Here is my attempt to do it:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.IO; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using A = DocumentFormat.OpenXml.Drawing; using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; using PIC = DocumentFormat.OpenXml.Drawing.Pictures; namespace DocWriter { class Program { static void Main(string[] args) { string strDoc = @"doc5.docx"; using (WordprocessingDocument myDoc = WordprocessingDocument.Create(strDoc, WordprocessingDocumentType.Document)) { myDoc.AddMainDocumentPart(); myDoc.MainDocumentPart.Document = new Document(); myDoc.MainDocumentPart.Document.Body = new Body(); AddPicHeader(myDoc); } } public static Header Mkpicheader(WordprocessingDocument doc, string relationshipId) { //Define the reference of the image. var element = new Drawing( new DW.Inline( new DW.Extent() { Cx = 990000L, Cy = 792000L }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 1" }, new DW.NonVisualGraphicFrameDrawingProperties( new A.GraphicFrameLocks() { NoChangeAspect = true }), new A.Graphic( new A.GraphicData( new PIC.Picture( new PIC.NonVisualPictureProperties( new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "oando-logo.png" }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri ="{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = relationshipId, CompressionState = A.BlipCompressionValues.Print }, new A.Stretch( new A.FillRectangle())), new PIC.ShapeProperties( new A.Transform2D( new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = 990000L, Cy = 792000L }), new A.PresetGeometry( new A.AdjustValueList() ) { Preset = A.ShapeTypeValues.Rectangle })) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" }); var header = new Header(); var paragraph = new Paragraph(); var run = new Run(); run.Append(element); paragraph.Append(run); header.Append(paragraph); return header; //newHeaderPart.Header = header; // wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); } public static void AddPicHeader(WordprocessingDocument doc) { ImagePart imgPart = doc.MainDocumentPart.AddImagePart(ImagePartType.Jpeg); var imagePartID = doc.MainDocumentPart.GetIdOfPart(imgPart); string imageFile = @"no-image.jpg"; using (Stream targetStream = imgPart.GetStream()) { using (FileStream sourceStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024]; int nrBytesWritten = sourceStream.Read(buffer, 0, 1024); while (nrBytesWritten > 0) { targetStream.Write(buffer, 0, nrBytesWritten); nrBytesWritten = sourceStream.Read(buffer, 0, 1024); } } } if (doc.MainDocumentPart.HeaderParts.Count() == 0) { //doc.MainDocumentPart.DeleteParts(doc.MainDocumentPart.HeaderParts); var newHeaderPart = doc.MainDocumentPart.AddNewPart<HeaderPart>(); var rId = doc.MainDocumentPart.GetIdOfPart(newHeaderPart); var headerRef = new HeaderReference(); headerRef.Id = rId; var sectionProps = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().LastOrDefault(); if (sectionProps == null) { sectionProps = new SectionProperties(); doc.MainDocumentPart.Document.Body.Append(sectionProps); } sectionProps.RemoveAllChildren<HeaderReference>(); sectionProps.Append(headerRef); newHeaderPart.Header = Mkpicheader(doc, imagePartID); newHeaderPart.Header.Save(); } } } }
Any help would be really really appreciated. Thank you!
emg.
Hi
I am working on a .NET 4.0 console application. I am trying to read the data from MS excel 2007 document. (file format in Xlsx)
I use the below code to load the data into datatable. It works fine if all the cells have values. But it does not work when one of the column has blank values.
Data gets shifted to left in the datatable. I will want to fill blank value for the column "Code" in the datatable.
Data in TestFile.xlsxFULL Name | PanID | Period | Year | Code | Type |
Name1 | 1 | 201301 | 2013 | 1 | |
Name2 | 2 | 201302 | 2014 | 2 | |
Name3 | 3 | 201303 | 2015 | 3 | |
Name4 | 4 | 201304 | 2016 | 4 |
WindowsBase version 4.0 and DocumentFormat.OpenXML dll reference added
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
public void Read2007Xlsx() { try { DataTable dt = new DataTable(); using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"D:\2007\Testfile.xlsx", false)) { WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart; IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild<SheetData>(); IEnumerable<Row> rows = sheetData.Descendants<Row>(); foreach (Cell cell in rows.ElementAt(0)) { dt.Columns.Add(GetCellValue(spreadSheetDocument, cell)); } foreach (Row row in rows) //this will also include your header row... { DataRow tempRow = dt.NewRow(); for (int i = 0; i < row.Descendants<Cell>().Count(); i++) { // tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1)); tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i)); } dt.Rows.Add(tempRow); } } dt.Rows.RemoveAt(0); //...so i'm taking it out here. } catch (Exception ex) { } } public static string GetCellValue(SpreadsheetDocument document, Cell cell) { SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart; if (cell.CellValue ==null) { return ""; } string value = cell.CellValue.InnerXml; if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) { return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText; } else { return value; } }
How to identify if a cell has blank value while reading Xlsx file using Open XML?
How to convert data in Xlsx file into dataset that has blank values using Open XML?
Thanks
Ashok
Hi
I am generating a spreadsheet from Open Xml from rows in a Sql Table. I am able to make the spreadsheet file but all the cells are like Text cells (including the column names). But what I wish to do is to add a Table in the spreadsheet and then add columns and rows inside this table. How can this be done??
Thanks