Quantcast
Channel: Open XML Format SDK forum
Viewing all 1288 articles
Browse latest View live

OpenXML Document in VB.NET Multiple Sheets

$
0
0

Hi,

I'm successfully creating a spreadsheet with one sheet from a dataview.

Now I'm trying to create multiple sheets from multiple dataviews.

I can't quite get it to add multiple sheets.

		Dim dv1 As DataView

		Dim sql() As String
		sql = Split(dv(x)("ps_sql"), ";")




		' create the workbook
		Dim Spreadsheet = SpreadsheetDocument.Create((TextBox1.Text + dv(x)("ps_filename").ToString().Replace(".", "_" + datestamp + ".")).ToString(), SpreadsheetDocumentType.Workbook)
		Spreadsheet.AddWorkbookPart()

		For sh = 0 To sql.Count - 1
			If sql(sh) <> "" Then
				Spreadsheet.WorkbookPart.Workbook = New Workbook()
				Spreadsheet.WorkbookPart.AddNewPart(Of WorksheetPart)()
				Spreadsheet.WorkbookPart.WorksheetParts.Last().Worksheet = New Worksheet()
				dv1 = GetData(sql(sh), connectionString)
				' create sheet data
				Spreadsheet.WorkbookPart.WorksheetParts.Last().Worksheet.AppendChild(New SheetData())
				' create header row
				Dim headerRow As New Row()
				For Each column As DataColumn In dv1.Table.Columns
					Dim cell = New Cell()
					cell.DataType = CellValues.String
					cell.CellValue = New CellValue(column.ColumnName)
					headerRow.AppendChild(cell)
				Next
				Spreadsheet.WorkbookPart.WorksheetParts.Last().Worksheet.Last().AppendChild(headerRow)

				' create data rows
				For Each dsrow As DataRow In dv1.Table.Rows
					Dim newRow = New Row()
					For Each col In dsrow.Table.Columns
						Dim cell = New Cell()
						'MsgBox(col.columnname)
						'MsgBox(col.datatype.ToString)
						Select Case col.DataType.ToString
							Case "System.Decimal"
								cell.DataType = CellValues.Number
							Case "System.Int32"
								cell.DataType = CellValues.Number
							Case "System.String"
								cell.DataType = CellValues.String
							Case "System.DateTime"
								cell.DataType = CellValues.Date
						End Select

						cell.CellValue = New CellValue(dsrow(col).ToString())
						newRow.AppendChild(cell)
					Next
					Spreadsheet.WorkbookPart.WorksheetParts.Last().Worksheet.Last().AppendChild(newRow)
				Next

				' save worksheet
				Spreadsheet.WorkbookPart.WorksheetParts.Last().Worksheet.Save()

				' create the worksheet to workbook relation
				Spreadsheet.WorkbookPart.Workbook.AppendChild(New Sheets())


				Dim s = New Sheet()

				s.Id = Spreadsheet.WorkbookPart.GetIdOfPart(Spreadsheet.WorkbookPart.WorksheetParts.Last())
				s.SheetId = CType(sh, UInt32Value)
				s.Name = "test" + sh.ToString
				'Spreadsheet.WorkbookPart.Workbook.GetFirstChild(Of Sheets)().AppendChild(s)
				Spreadsheet.WorkbookPart.Workbook.Sheets.AppendChild(s)

				' save workbook
				Spreadsheet.WorkbookPart.Workbook.Save()

			End If
		Next
		Spreadsheet.Close()

Could someone kindly point me in the right direction please?

Many Thanks

Ted



Does Microsoft support to export embedded object from excel, such as pdf, jpg, etc?

$
0
0

Hi,

I am trying to find a way to read embedded object from excel, such as pdf, jpg. Does Microsoft support that?  

Thanks,

how can i update charts' data in word document by using OpenXML

$
0
0

There was 18 charts In my word document . I can get the charts by code like this:

private MainDocumentPart mainDocPart;

......

ChartPart c_p = mainDocPart.ChartParts.FirstOrDefault();

Then I can update the data of charts.But the problem is this:

I have 18 charts In the document , and the charts index was random.So I can't get the chart by index yet:

ChartPart c_p = mainDocPart.ChartParts.ElementAt(index);//index is Integer Value

So can I appoint the ID or Name for each of the 18 charts?And Can I get Them By ID or Name?

I can update one Charts data by Openxml.If neither,How can I update datas for so many charts by OpenXml?


赵召


Get absolute coordinates a child shape

$
0
0

Sorry for my English.

A PowerPoint slide contains a group shape (grpSp) with following coordinates:

<a:offy="2058985"x="244799"/><a:extcy="2264343"cx="7118946"/><a:chOffy="2058986"x="244799"/><a:chExtcy="1942187"cx="5727249"/>

This group shape contains a child shape (sp) with following coordinates:

<a:offy="3084512"x="244799"/><a:extcy="916661"cx="1710237"/>

After ungrouping the child shape contains follow coordinates:

<a:offy="2058986"x="244799"/><a:extcy="1064224"cx="2545581"/>

As you can see coordinates are changed - converting to absolute coordinate on the slide.

I cannot programmatically to make the formula to get these absolutely coordinates. Which formula should I use to convert a child shape's coordinates to absolute as shown in the example (cx="1710237" => "2545581")?

How to read VBA code from macro-enabled document(.DOCM) using openXML in C# ?

$
0
0

I need to read VBA code which is included in macro enabled document(.DOCM) file using openXML in c#.

I have tried following code but it returns weird string.

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
{

       VbaProjectPart vbaPart = wordDoc.MainDocumentPart.VbaProjectPart;

       Stream stream = vbaPart.GetStream();

       using(StreamReader reader = new StreamReader(stream,Encoding.UTF8))

      {

          string vbaData = reader.ReadToEnd();

      }

}

Any help would be appreciated.

Thanks!

Error opening xlsx file in office 2010 when saved through Open Xml format

$
0
0

We have added DataValidations to the existing excel file and saved the Workbook and getting an error when trying to open the files saved with Open XML Format in MS Office 2010.

Error Msg - 'Excel found unreadable content'

Although it gets opened in other tools.




Copy chart color schema to another chart

$
0
0

Sorry for my English :)

A presentation slide contains two charts: Input and Template

Based on those two charts I need get third Output chart which will contain chart type fromInput chart and color schema from Template chart as shown in the figure.

How can I achieve such result with Open XML SDK?


OpenXML generated file wont open in MS Spreadsheet Compare tool and Excel "Open and Repair" also reports a problem

$
0
0

We are trying to build new process to auto generate Excel files using OpenXML (2.8.1.0). The very basic XLSX file will open in Excel, but when I try to use the MS tool Spreadsheet Compare tool, it can't open the file. The error we are getting is

"Error opening workbook. Attempted to read past the end of the stream"

If I open the OpenXML generated file in Excel and save it first, the file can now be opened by the Spreadsheet Comparison tool. Excel is fixing/adding something to the file that is missing from OpenXML generated file.

I used this MSDN sample code as a very basic starting point to help demonstrate the problem
https://msdn.microsoft.com/en-us/library/office/ff478153.aspx

The goal is to use the Spreadsheet comparison tool to make sure what we are generating is matching the old process that created the same file.

I ran the file the "Open and Repair" in the Excel file open dialog, and it gives me this report on the original file generated from the above sample.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error260080_01.xml</logFileName><summary>Errors were detected in file 'C:\TEMP\testing.xlsx'</summary><additionalInfo><info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info></additionalInfo></recoveryLog>

Thank you 


Closed XML getting error of DocumentFormat.OpenXml Dll.

$
0
0

Hi,

 i have implemented Export to excel functionality in my dot net project. I have used Closed XML api which is based on Open XML ,When i run my code locally for exporting my dataset to excel using Closed XML it works fine.But same project i have deployed on server where my export functionality doesn't work. I have all related DLL in my project. 

 i.e ClosedXML.dll , DocumentFormat.OpenXml

Error i am getting on server is : 

System.IO.FileNotFoundExceptionCould not load file or assembly 'DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Please help me to resolve this issue and provide your suggestions.

Thanks,

Ketan

System.IO.FileFormatException: File contains corrupted data

$
0
0

Hi!

I use OpenXml library to count the number of pages in the pptx files uploaded by user. 90% of times it success but 10% of time it fails and give the error in the title.

The function I call is:

PresentationDocument.Open(file.InputStream, false), where the parameter "file" in this function is a Telerik class, Telerik.Web.UI.UploadedFile.

The stack trace is: 

System.IO.FileFormatException: File contains corrupted data.

   at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.ValidateZip64TriggerValues()

   at MS.Internal.IO.Zip.ZipIOBlockManager.CreateLoadZip64Blocks()

   at MS.Internal.IO.Zip.ZipIOBlockManager.get_Zip64EndOfCentralDirectoryBlock()

   at MS.Internal.IO.Zip.ZipIOBlockManager.get_CentralDirectoryBlock()

   at MS.Internal.IO.Zip.ZipArchive.GetFiles()

   at System.IO.Packaging.ZipPackage.ContentTypeHelper..ctor(ZipArchive zipArchive, IgnoredItemHelper ignoredItemHelper)

   at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming)

   at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)

   at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(Stream stream, Boolean readWriteMode)

   at DocumentFormat.OpenXml.Packaging.PresentationDocument.Open(Stream stream, Boolean isEditable, OpenSettings openSettings)

Another detail to provide is that when the code run locally it success 100% of the time, but when run on the server it gives this error. 

Any help is appreciated!

Copy chart from one presentation to another presentation

$
0
0

Sorry for my English :)

I try to copy a chart element from one presentation to another with the same position

using C =DocumentFormat.OpenXml.Drawing.Charts;

namespace OpenXmlApp{publicclassShapeReader{publicstaticvoidCopyChart(string sourPrePath,string destPrePath){
            using (var sourDoc =PresentationDocument.Open(sourPrePath,false)){
                using (var destDoc =PresentationDocument.Open(destPrePath,true)){// Get copy of graphic frame.var sourGraphicFrameCopy = sourDoc.PresentationPart.SlideParts.First().Slide.CommonSlideData.ShapeTree.GetFirstChild<P.GraphicFrame>().CloneNode(true);// Add copy of graphic frame to destinition slide.var destSlidePart = destDoc.PresentationPart.SlideParts.First();var destShapeTree = destSlidePart.Slide.CommonSlideData.ShapeTree;
                    destShapeTree.Append(sourGraphicFrameCopy);// Add chart part to destinition slide.var sourChartPart = sourDoc.PresentationPart.SlideParts.First().ChartParts.First();var addedChartPart = destSlidePart.AddNewPart<ChartPart>();
                    addedChartPart.FeedData(sourChartPart.GetStream());// Link added graphic frame and added chart part.var chartRef = sourGraphicFrameCopy.Descendants<C.ChartReference>().SingleOrDefault();var addedChartPartId = destSlidePart.GetIdOfPart(addedChartPart);
                    chartRef.Id= addedChartPartId;

                    destDoc.Save();}}}

but this code just broke presentation - PowerPoint tries to restore the result presentation.

How correctly copy chart element?

Open XML Text is not replacing after editing word document.

$
0
0

Hi, I am working with OpenXML and stuck in a issue.

First I am creating the word document from template file.

Then using following code for mail merge

 Using docGenerated As WordprocessingDocument = WordprocessingDocument.Open(_targetFileName, True)
                        docGenerated.ChangeDocumentType(WordprocessingDocumentType.Document)

                        For Each field As FieldCode In docGenerated.MainDocumentPart.RootElement.Descendants(Of FieldCode)()
                            Dim fieldNameStart = field.Text.LastIndexOf(FieldDelimeter, System.StringComparison.Ordinal)
                            Dim fieldname = "FirstName"
                            Dim fieldValue ="Test"
                            For Each run As Run In docGenerated.MainDocumentPart.Document.Descendants(Of Run)()

                                For Each txtFromRun As Text In run.Descendants(Of Text)().Where(Function(a) a.Text.ToLower() = "«" & fieldname.ToLower() & "»")
                                    txtFromRun.Text = fieldValue
                                Next
                            Next
                        Next
                        Dim settingsPart As DocumentSettingsPart = docGenerated.MainDocumentPart.GetPartsOfType(Of DocumentSettingsPart)().First()
                        Dim oxeSettings = settingsPart.Settings.Where(Function(a) a.LocalName = "mailMerge").FirstOrDefault()

                        If oxeSettings IsNot Nothing Then
                            settingsPart.Settings.RemoveChild(oxeSettings)
                            settingsPart.Settings.Save()
                        End If

                        docGenerated.MainDocumentPart.Document.Save()
                        docGenerated.Close()
                    End Using

After that I am using AltChunk to add text from template file to existing word document and then trying about code for mail merge.

But after adding text merging is not working for second page.

Please suggest what I am doing wrong.

How to get all text in presentation without Title?

$
0
0

Hello!

I have an issue. I want to receive text from a slide without Title. In an example "How to: Get all the text in all slides in a presentation" we recieve whole text by tag <t> in XML, title + text. What can you advice in this situation?

Compute max number of characters for a shape

$
0
0

Sorry for my English :)

I know shape's (on the slide) width, height, and its text font size. Is there a way to definemax number of characters which shape can contain?

I need just an approximate number because I realize to find out exact number I also should consider parameters like line spacing. 










Can we use indexing and .Count with OpenXML?

$
0
0

I am told that OpenXML is very fast and am porting one of my apps to it. One of the operations is rather common: to iterate through the worksheet names. I am used to doing this sort of thing with a for loop.

However, the example that I found here:

https://docs.microsoft.com/en-us/office/open-xml/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet

performs the iteration using a foreach() statement.

static void Main(string[] args)
{
   var results = GetAllWorksheets(DEMOFILE);
   foreach (Sheet item in results)
   {
     Console.WriteLine(item.Name);
   }
}

I am definitely partial to for loops, and being able to .Count items. Are those essential features missing fromOpenXML?

TIA




how to make openxml insert spreadsheet rows most efficiently

$
0
0

I use OpenXML v 2.8.1.0 to create an excel report for a web site. Spreadsheet has 22 columns. Takes 30 seconds to render 15,000 rows, but that's too long for a web page. Can I do this more efficiently?

Code snippet is below (left out parts not germane to the issue). Suspect I'm inefficient in all that looping through each cell to set its cellreference, and then setting each row's cellreference as well.

I left out code where I open the spreadsheet I am populating - it contains headers and a sample detail row, which has all formatting I want but all values are blank.

In code I clone that row, set values and cellreference for each cell, set rowreference for the row, insert the row, then get the next row of data from the database and repeat.

Or is 500 rows per second about as fast as OpenXML is capable of?

Thanks.

public class MyReport
{
    public byte[] Get(List<dbRow> dbRows)
    {
        // dbRows is the result of "Select col0, col1, ... col21 from dbTable"

        // first 6 rows are the report headers
        // row 7 is the blank detail row.
        Row templateDetailRow = sheetData.Elements<Row>().Where(r => r.RowIndex == 7).First();
        // start inserting data rows at row number 8
        uint currentRowPointer = sheetData.Elements<Row>().LastOrDefault().RowIndex + 1; // start adding rows after the current last row
        Row currentBottomRow = sheetData.Elements<Row>().LastOrDefault(); // initialize to last row before we start adding rows

        foreach (dbRow r in dbRows)
        {
            Row newRow = (Row)templateDetailRow.Clone();
            List<Cell> cells = newRow.Elements<Cell>().OrderBy(c => c.CellReference.Value).ToList();
            SetCellsInRow(cells, r, currentRowPointer);
            newRow.RowIndex = currentRowPointer;
            InsertRow(sheetData, newRow);
            currentRowPointer++;
        }

    }
    private void SetCellsInRow(List<Cell> cells, dbRow source, uint rowIndex)
    {
        SetCell(cells[0], source.string0, rowIndex);
        SetCell(cells[1], source.int1, rowIndex);
        SetCell(cells[2], source.string2, rowIndex);
        SetCell(cells[3], source.string3, rowIndex);
        SetCell(cells[4], source.string4, rowIndex);
        SetCell(cells[5], String.Format("{0:MM/dd/yyyy}", source.date5), rowIndex);
        SetCell(cells[6], source.string6, rowIndex);
        SetCell(cells[7], source.int7, rowIndex);
        SetCell(cells[8], source.string8, rowIndex);
        SetCell(cells[9], source.string9, rowIndex);
        SetCell(cells[10], source.date10.ToString("MM/dd/yyyy"), rowIndex);
        SetCell(cells[11], String.Format("{0:MM/dd/yyyy}", source.date11), rowIndex);
        SetCell(cells[12], String.Format("{0:MM/dd/yyyy}", source.date12), rowIndex);
        SetCell(cells[13], source.string13, rowIndex);
        SetCell(cells[14], String.Format("{0:MM/dd/yyyy}", source.date14), rowIndex);
        SetCell(cells[15], source.int15 ?? 0, rowIndex);
        SetCell(cells[16], String.Format("{0:MM/dd/yyyy}", source.date16), rowIndex);
        SetCell(cells[17], source.string17, rowIndex);
        SetCell(cells[18], source.string18, rowIndex);
        SetCell(cells[19], source.int19, rowIndex);
        SetCell(cells[20], source.string20, rowIndex);
        SetCell(cells[21], source.string21, rowIndex);
    }

    private void SetCell(Cell theCell, string val, uint rowIndex)
    {   // a NON-SHARED string is going in to the cell
        theCell.CellValue = new CellValue(val);
        theCell.DataType = new EnumValue<CellValues>(CellValues.String);
        theCell.CellReference = Regex.Replace(theCell.CellReference, @"\d+", rowIndex.ToString());
    }

    private void SetCell(Cell theCell, int val, uint rowIndex)
    {    // an int is going in to the cell
        theCell.CellValue = new CellValue(val.ToString());
        theCell.DataType = new EnumValue<CellValues>(CellValues.Number);
        theCell.CellReference = Regex.Replace(theCell.CellReference, @"\d+", rowIndex.ToString());
    }

    private static void InsertRow(SheetData sheetData, Row row)
    {
        sheetData.InsertAfter(row, currentBottomRow);
        currentBottomRow = row;
    }
}


Found for fastest, most efficient way to handle large Excel files. Need to make it even faster.

$
0
0

Hello:

This is a follow up to the following thread:

  https://social.msdn.microsoft.com/Forums/en-US/4418a7ae-3269-4697-86e1-1cc9250f94a6/looking-for-fastest-most-efficient-way-to-handle-large-excel-files?forum=vsto

I found this code segment which is the answer to my prayers:

// The SAX approach.
static void ReadExcelFileSAX(string fileName)
{
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
    {
        WorkbookPart  workbookPart  = spreadsheetDocument.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

        OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
        string text;
        while (reader.Read())
        {
            if (reader.ElementType == typeof(CellValue))
            {
                text = reader.GetText();
                Console.Write(text + " ");
            }
        }
        Console.WriteLine();
        Console.ReadKey();
    }
}

   https://docs.microsoft.com/en-us/office/open-xml/how-to-parse-and-read-a-large-spreadsheet

That is exactly what is needed to traverse a spreadsheet, row by row. My only question is this: the code above seems to retrieve the values from all cells? Regardless of location? Needless to say, we developers use 2-dimensionalindexing.

How to convert that optimized code to retrieval by worksheet name and coordinates? Preferably numerical.

TIA





Insert a picture into a header or footer of a word processing doc

$
0
0

Hi team,

I have referred to the link http://msdn.microsoft.com/en-us/library/office/bb497430.aspx to add image part in the word doc

public static void InsertAPicture(string document, string fileName)
{
    using (WordprocessingDocument wordprocessingDocument = 
        WordprocessingDocument.Open(document, true))
    {
        MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

        ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

        using (FileStream stream = new FileStream(fileName, FileMode.Open))
        {
            imagePart.FeedData(stream);
        }

        AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
    }
}

private static void AddImageToBody(WordprocessingDocument wordDoc, 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 = "New Bitmap Image.jpg" },
                                 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" });

   // Append the reference to body, the element should be in a Run.
   wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}

how can i add image to the header or footer part using the same concept here. Please help me out

 

Harish

Get font size for slide shape

$
0
0

A shape which is located on the slide has a paragraph and this paragraph has A.Run instance which property RunProperties.FontSize is null.

This instance also contains text. How can I get his font size? Maybe if <g class="gr_ gr_66 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="66" id="66">FontSize</g> is null then this instance uses some default <g class="gr_ gr_41 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="41" id="41">FontSize</g>, but then where store this value? 


After save document, I can not open saved document OpenXML SDK 2.5

$
0
0

After I save document (object Document open myfile.docx and save it as myfileEdited) Document.SaveAs("myfileEdited.docx"); or I use Close(); when I call 

using (WordprocessingDocument Document2 = WordprocessingDocument.Open("myfileEdited.docx", true)) 
{
// ...
}

it crash here and I got message 

"Unhandled Exception: System.IO.IOException: The process cannot access the file 'path to file' because it is being used by another process."


Viewing all 1288 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>