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

Open XML Reading Excel file using Powershell

$
0
0

Hello All,

I'm new to OpenXML and my objective is to read an excel document using Powershell. The reading of the document will be on a server where excel is not installed hence the use of OpenXML. The challenge I'm having is understanding the object model in relation to using it in powershell. Below is what I have written so far and I'm stuck at the point of reading each cell. Even though I have content in the excel file it does not appear when I loop through the cells for a given row as illustrated below. Any ideas what I'm doing incorrectly below? This needs to be written in powershell and also to use openxml. The plan is to ultimately use powertools for openxml for other objectives.   Thank you for your help

cls
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml")
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Packaging")
[Reflection.Assembly]::LoadWithPartialName("DocumentFormat.OpenXml.Spreadsheet")
[Reflection.Assembly]::LoadWithPartialName("OpenXmlPowerTools")

[DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]$Document = $null
$Document = [DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]::Open("C:\temp\Book1.xlsx", $true)
[DocumentFormat.OpenXml.Packaging.WorkbookPart]$WorkBookPart = $Document.WorkbookPart
[DocumentFormat.OpenXml.Spreadsheet.Sheets]$WorkSheets = $null
$WorkSheets = $WorkBookPart.Workbook.Sheets
foreach ($WorkSheet in $WorkSheets)
{
[DocumentFormat.OpenXml.Spreadsheet.SheetData]$SheetData = $null
$SheetData = $WorkSheet.get_FirstChild()
[DocumentFormat.OpenXml.Spreadsheet.Row]$Row = $null
foreach ($Row in $SheetData)
{
[DocumentFormat.OpenXml.Spreadsheet.Cell]$Cell = $null
foreach ($Cell in $Row)
{
Write-Host $Cell.CellValue.Text
}
}
}

$Document.Close()



DrawingML Charts rendering

$
0
0

Hi,

Is there any way to convert DrawingML Chart or Diagram to jpg (or other similar graphic format) using the Open XML Format SDK? 
Or maybe without Open XML Format SDK. All I need is to render charts and diagrams. What can be used for this purpose?

Any help will be greatly appreciated. 

Create MS Word files programmatic - How to position the content with coordinates

$
0
0

Hello,

We are developing C# code to generate open office word files programmatic way from a post script file. The input comes from PDF generation process and it will have coordinates data to position the contents properly. This is useful in positioning the content in a PDF layout and it does great job there. However, we cannot position the content on word page based on the coordinates. The input content may have paragraphs/tables/images/headers/footers etc. We have been able to handle tables and images properly since those can be positioned in the landscape. But the paragraph text does not. Do we have any option in MS-word to do that.

One option we tried is putting the frames for paragraph content however, if we edit a frame and add more content it will overlap with the next frame. That did not turn out to be a choice :(

Target office versions: 2007/2010.

Usage: Open XML Format SDK 2.5 

Regards,

Manju.


manjunath

Cell Strikethough - Check For

$
0
0

This seems such a simple problem, but I have Googled myself to a standstill.

I wish to return the contents of an Excel cell, and check whether the font has a Strikethrough property. This is my flag to ignore that row. I am using ClosedXML and the following code: 

XLWorkbook wb = new XLWorkbook(fs);
IXLWorksheet ws = wb.Worksheet(pstrXLSWorksheetName);
if (ws.Cell(lstrCellAddressPriKey).Style.Font.Strikethrough == true)
{
pintTotalStrikethroughsIgnored++;
lblnProceed = false;
}

This works but the performance is appalling. Over severall hundred rows it turns a minute into an hour.

Can anyone provide a sample not using ClosedXML?
bool IsStrikethrough(cell) - or (cellAddress)

Thanks

Dale

When Support Windows RunTime !!?

$
0
0

I want to use  Open XML SDK in Windows Phone 8.1 App ,But I cant do it , because don't support Windows Runtime !!

do you have any idea to create or edit office file !!

Word 2010: Save as PDF causes XXE problems

$
0
0

My company has been experiencing problems with Word documents saved as PDFs.  The process appears to inject external XML Entities (XXE) into the document that make our firewall flag them as threats.  

It appears to be only from documents saved as PDF using an Office application's Save As dialog.

For the time being, I've told my users to stop making PDFs this way, and instead print through the PDF printer that came with Adobe Acrobat Pro.  None of those PDFs cause the problem.

But it's often difficult to get users to do something if it's more complicated, and the complaint usually comes from a website editor who is blocked from uploading the PDF, far down the chain from the person who created the PDF.  Sometimes the creator is from a different organization.

I'm not interested in discussing firewall configuration in a group dedicated to Office, but I would like to know what it is about Office's save as PDF that puts this unneccessary stuff in the resulting PDFs. 


Track changes Content

$
0
0

Am building an application that track changes that a user makes. Am using C# . How can i track changes a user did and get the changes they made

Creating of new table with help OpenXml and writinig to it.

$
0
0

Hallo.

I create 5 same copies of table in document. They create without problem.

For poc = 0To 5

               Dim tableAsNewTable(doc.MainDocumentPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Table)().ElementAt(0).CloneNode(True))

               Dim mainDocumentPartAsMainDocumentPart = doc.MainDocumentPart()

               Dim bodyAsBody = mainDocumentPart.Document.AppendChild(NewBody())

               Dim paraAsParagraph = body.AppendChild(NewParagraph())

               Dim runAsRun = para.AppendChild(NewRun())

               run.AppendChild(table)

               'run.AppendChild(New Break())

               mainDocumentPart.Document.Save()

           Next

The problem start, when i want to write text to table. 

For poc = 0To 6

               Dim tableAsTable

               Dim rowAsTableRow

               Dim cellAsTableCell

               Dim pAsParagraph

               Dim rAsRun

               Dim tAsText

               table = doc.MainDocumentPart.Document.Body.Elements(OfTable)().ElementAt(poc)'it show me error here, during second cycle!!!

               row = table.Elements(OfTableRow)().ElementAt(1)

               cell = row.Elements(OfTableCell)().ElementAt(0)

               p = cell.Elements(OfParagraph)().First()

               r = p.Elements(OfRun)().First()

               t = r.Elements(OfText)().First()

               t.Text = poc & "XYZ"

           Next

Text write only in to table, that was already in document. I use this table as template.

When i write text  to first created table, this table shows error.

table = doc.MainDocumentPart.Document.Body.Elements(OfTable)().ElementAt(poc)

Additional information: Specified argument was out of the range of valid values.

It looks to me, as if it can't find these new tables for writing text. What i am doing wrong during creating tables? When i manualy coppy tables to document, it write text to it correctly. Problem is only when i create them through my code .

Thank you for your answer.

  


C# openxml sdk convert all wmf and emf images found in a docx into png and replace the occurences in all corresponding xmls.

$
0
0

I am using openxml sdk to read and manipulate docx.

I am able to iterate through all the images found in a docx and my task is to replace all the wmf/emf images into png or jpg.

string sourceFile="@D:\temp\sample.docx";
using (WordprocessingDocument myDocument = WordprocessingDocument.Open(sourceFile, true))
{
 var imageParts = myDocument.MainDocumentPart.ImageParts;
 foreach (ImagePart imagePart in imageParts)
 {
   var uri = imagePart.Uri;
   var filename = uri.ToString().Split('/').Last();
   if (imagePart.ContentType.Equals("image/x-wmf"))
   {
      Image img = Image.FromStream(imagePart.GetStream());
      /*
        Now I need to convert the image format from WMF or
        EMF to PNG and replace the output in all the xml.
      */
   }

 }
}

Determine if Font change is inside a table - Word 2010 - Vs2010 - Vb.net

$
0
0

Starting to move some routines from vba to Open XML.

I am using the following to identify Font changes:
Dim l as List(Of RunFonts) = (Doc.Descendants(Of RunFonts)()).ToList

I would now like to iterate thru this list and identify any occurrences
that occurr within a table. An example or reference would be greatly
appreciated.




Tim

about CT_Xf

$
0
0

Hi dear all,

1. If CT_Xf.apply* , for example, CT_Xf.applyNumberFormat is missing , what does it mean ? true or false?

2. For a record in cellXfs CT_Xf.xfid can miss ?

many thanks !!!


Getting Symbols from the Word document

$
0
0

Hi Everyone,

I am creating one application, which is creating a XML from the paragraphs of the word document. Currently, I am getting stuck at a point where a symbol is provided in the word text.

Basically the input word document contains lots of equations, so at few places, they have used trigonometry angles, have a look at the image below:

I am not been able to create the text properly. How do i put this symbol in my XML text? Any suggestions?

Thanks,


Shahab Abbasi


Can't install -- Open XML SDK 2.5 is not supported on .NET Framework Version 4.5 - is there a workaround?

$
0
0

My corporate client provided me a high powered laptop (with secure network access) for development purposes.   When I attempt to install the OpenXMLSDKV25.msi it reports "You should have .NET Framework 4.0 installed before you setup Open XML SDK 2.5..."

Visual Studio shows that my laptop has Microsoft .NET Framework Version 4.5.50709 installed

Is there a work-around so that I can get it installed? 


MCAD.NET C# - http://www.Global-webnet.com/Blog

OpenXml adding table to the middle of document.

$
0
0

I copy by this code a table and i add it to document.

Using Doc As WordprocessingDocument = WordprocessingDocument.Open("D:\Projekty\Visual Basic 2013\Zdrojáky\OpenXML skuska\OpenXML skuska6\Sablona2.docx", True)

            For poc = 0 To 1
                Dim table As New Table(Doc.MainDocumentPart.Document.Body.Descendants(Of Table)().FirstOrDefault().CloneNode(True))

                For Each tr As TableRow In table.Descendants(Of TableRow)()
                    For Each tc As TableCell In tr.Descendants(Of TableCell)()
                        Dim run As New Run
                        run.Append(New Text("Hello"))
                        tc.Descendants(Of Paragraph)().FirstOrDefault().Append(run)
                    Next
                Next

                Doc.MainDocumentPart.Document.Body.Append(table)
                Doc.MainDocumentPart.Document.Body.Append(New Paragraph())
            Next

But i have one problem. Table that i copping is in the middle of document. And need to place other tables right behind it.  But now it place them in the bottom side of document. How to add tables to the middle of document.

Thank you for your answer.


Create Powerview from existing excel template file using Open XML in C#

$
0
0

Hi,

I have created one Excel file with two sheets and saved it in location.

1. raw data.
2. power view chart based first sheet raw data.

In c#. I will open the saved excel file and write the new data in the first sheet and do refresh the second power view sheet and saved in another location.

How could i achieve it in OpenXML.

Anybody help me on it.

I have done the same in InterOp. but the bottle neck is, It is physically opening the template file. It is not suppose to happen.

Thanks & Regards
Suresh Sankaran


Solution: How to AutoFit Excel Content

$
0
0

I, like most, am new to Open XML.  I was trying to find a way to size the column to my largest item.  I mostly found that the current spec doesn't support it automatically.  After poking around I found a formula which I rework to calculate the width based on the pixel width of the string.  I then found a way to size the column.

Here is the complete source code to do it.  I should mention that I am NOT searching for the largest string in the column but rather calculating 1 item.  Haven't quite figured out how to do search yet.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace AutoFit
{
  class Program
  {
   static void Main(string[] args)
   {
     string docName = @"D:\Temp\MyFirstExcel.xlsx";

     // Create a Wordprocessing document.
     using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(docName, SpreadsheetDocumentType.Workbook))
     {
      // Add a WorkbookPart to the document.
      WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
      workbookpart.Workbook = new Workbook();

      // Add a WorksheetPart to the WorkbookPart.
      WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
      worksheetPart.Worksheet = new Worksheet();

      // ####################################
      //   IMPORTANT STUFF
      // ####################################

      string strText = "This is some really, really long text to display.";
      double width = GetWidth("Calibri", 11, strText);

      string strText2 = "123";
      double width2 = GetWidth("Calibri", 11, strText2);

      Columns columns = new Columns();
      columns.Append(CreateColumnData(2, 2, width));
      columns.Append(CreateColumnData(3, 3, width2));
      worksheetPart.Worksheet.Append(columns);

      // ####################################
      //   END OF IMPORTANT STUFF
      // ####################################

      SheetData sd = new SheetData();
      worksheetPart.Worksheet.Append(sd);

      // Add Sheets to the Workbook.
      Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());


      // Append a new worksheet and associate it with the workbook.
      Sheet sheet = new Sheet()
      {
        Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
        SheetId = 1,
        Name = "mySheet"
      };
      sheets.Append(sheet);



      // Add Data
      Row row = new Row();

      Cell cell;

      // String
      cell = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, "B2");
      cell.CellValue = new CellValue(strText);
      cell.DataType = CellValues.String;


      // Number
      int count = 123;
      cell = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, "C2");
      CellValue cellValue = new CellValue(count.ToString());
      cell.CellValue = cellValue;
      cell.DataType = CellValues.Number;

      workbookpart.Workbook.Save();

      // Close the document.
      spreadsheetDocument.Close();
     }
   }

   private static double GetWidth(string font, int fontSize, string text)
   {
     System.Drawing.Font stringFont = new System.Drawing.Font(font, fontSize);
     return GetWidth(stringFont, text);
   }

   private static double GetWidth(System.Drawing.Font stringFont, string text)
   {
     // This formula is based on this article plus a nudge ( + 0.2M )
     // http://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.column.width.aspx
     // Truncate(((256 * Solve_For_This + Truncate(128 / 7)) / 256) * 7) = DeterminePixelsOfString

     Size textSize = TextRenderer.MeasureText(text, stringFont);
     double width = (double)(((textSize.Width / (double)7) * 256) - (128 / 7)) / 256;
     width = (double)decimal.Round((decimal)width + 0.2M, 2);

     return width;
   }

   private static Column CreateColumnData(UInt32 StartColumnIndex, UInt32 EndColumnIndex, double ColumnWidth)
   {
     Column column;
     column = new Column();
     column.Min = StartColumnIndex;
     column.Max = EndColumnIndex;
     column.Width = ColumnWidth;
     column.CustomWidth = true;
     return column;
   }

   // Given a Worksheet and a cell name, verifies that the specified cell exists.
   // If it does not exist, creates a new cell.
   private static Cell CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName)
   {
     string columnName = GetColumnName(cellName);
     uint rowIndex = GetRowIndex(cellName);

     IEnumerable<Row> rows = worksheet.Descendants<Row>().Where(r => r.RowIndex.Value == rowIndex);
     Cell cell;

     // If the Worksheet does not contain the specified row, create the specified row.
     // Create the specified cell in that row, and insert the row into the Worksheet.
     if (rows.Count() == 0)
     {
      Row row = new Row() { RowIndex = new UInt32Value(rowIndex) };
      cell = new Cell() { CellReference = new StringValue(cellName) };
      row.Append(cell);
      worksheet.Descendants<SheetData>().First().Append(row);
      worksheet.Save();
     }
     else
     {
      Row row = rows.First();

      IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => c.CellReference.Value == cellName);

      // If the row does not contain the specified cell, create the specified cell.
      if (cells.Count() == 0)
      {
        cell = new Cell() { CellReference = new StringValue(cellName) };
        row.Append(cell);
        worksheet.Save();
      }
      else
        cell = cells.First();
     }

     return cell;
   }

   // Given a cell name, parses the specified cell to get the column name.
   private static string GetColumnName(string cellName)
   {
     // Create a regular expression to match the column name portion of the cell name.
     Regex regex = new Regex("[A-Za-z]+");
     Match match = regex.Match(cellName);

     return match.Value;
   }

   // Given a cell name, parses the specified cell to get the row index.
   private static uint GetRowIndex(string cellName)
   {
     // Create a regular expression to match the row index portion the cell name.
     Regex regex = new Regex(@"\d+");
     Match match = regex.Match(cellName);

     return uint.Parse(match.Value);
   }
  }
}

Wrap text in header in word using Open XML SDK(C#)

$
0
0

Hello All,

I am using open xml format SDK to generate word document using c#. One of the issue I am facing is wrapping text in the header. Existing text is shown half in one line and another half of the text in another line. Need to make sure that the text is shown in the next line using wrapping.

Please guide me on this.

Here is the code I am using for it.

Run run8 = new Run() { RsidRunProperties = "0068783B", RsidRunAddition = "0068783B" };

            RunProperties runProperties8 = new RunProperties();
            RunStyle runStyle1 = new RunStyle() { Val = "tablecopy" };
            RunFonts runFonts8 = new RunFonts() { Ascii = "Arial", HighAnsi = "Arial", ComplexScript = "Arial" };
            Color color5 = new Color() { Val = "333333" };
            FontSize fontSize8 = new FontSize() { Val = "20" };
            FontSizeComplexScript fontSizeComplexScript6 = new FontSizeComplexScript() { Val = "20" };

            runProperties8.Append(runStyle1);
            runProperties8.Append(runFonts8);
            runProperties8.Append(color5);
            runProperties8.Append(fontSize8);
            runProperties8.Append(fontSizeComplexScript6);
            runProperties8.Append(wr);
            Text text7 = new Text();
            if (regionname != string.Empty)
            {
                text7.Text = regionname;
            }
            else
            {
                text7.Text = "";
            }
            
            run8.Append(runProperties8);
            run8.Append(text7);

How to get Document.OpenXML Version=2.5.5631.0 ?

$
0
0

Hi

I am trying to have Document.OpenXML Version=2.0.5022.0 because i am having this error when i try to run my project;

'ClosedXML, Version=0.76.0.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b' uses

'DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

which has a higher version than referenced assembly

'DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

Do i need to get Document.open.xml Version=2.0.5022.0 , if so , how can i find this dll?

[if you provide a download link that would be great ..]

Thanks


Windows services can't used Interop that is true ?

$
0
0

Dear All,

For my research, i know that windows services can't used Interop for the follow link :

http://stackoverflow.com/questions/13479164/office-interop-does-not-work-in-windows-service

I want to make sure it,can any one get me some detail about this or solve the issue below :

I write an tool to save the PowerPoint slide to image,

you can refer to : http://stackoverflow.com/questions/2972263/ppt-slides-to-images

and it work fine if i start it with an console project.

but when i change it to an windows services , i found that it can't work any more.

the error message :

System.Runtime.InteropServices.COMException (0x80004005): PowerPoint could not open the file.
   in Microsoft.Office.Interop.PowerPoint.Presentations.Open(String FileName, MsoTriState ReadOnly, MsoTriState Untitled, MsoTriState WithWindow)


Code Sample to put a date in Excel in C# using OpenXML SDK.

$
0
0

Hi,

I am looking for a simple code sample to set a cell to a Date value of the format "dd/mm/yy" - set to the English (Australian) locale.

Thanks,

Ward.

Viewing all 1288 articles
Browse latest View live


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