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

Difficulties Updating Columns Collection In Worksheet Using SAX

$
0
0

Hey guys,

I am working on a project where I am using a DataReader to read large amounts of data (100,000+ rows, 20+ column) and am streaming those into a worksheet using the SAX OpenXmlWriter methods to avoid high memory usage.  This is working very fast and efficiently so far as I can tell.  However, as I am writing these values I am also storing the maximum length outputted in each column so I can then go on and update the Columns collection in the worksheet to set appropriate default widths when the spreadsheet is opened in Excel.  Very frustratingly the Columns collection is BEFORE the SheetData meaning that there seems to be no way to update it after writing all my data!  If I try to access the Columns collection via the DOM then it loads the whole spreadsheet into memory and causes my app to crash with an OutOfMemoryException.

Do you guys know of any clever way of updating the Columns collection once the SheetData has finished being outputted without forcing the whole document to be loaded into memory or having to go through the WHOLE spreadsheet with an OpenXmlReader and then output it all again to a new sheet with a separate OpenXmlWriter? Any help would be much appreciated.

Cheers,

James.


Problem to re-open Excel file

$
0
0
Hi, 
I've got exception like
System.IO.IOException was unhandled
  HResult=-2147024864
  Message=The process cannot access the file 'C:\dp13\New0.xlsx' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
       at MS.Internal.IO.Zip.ZipArchive.OpenOnFile(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
       at System.IO.Packaging.ZipPackage..ctor(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
       at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, Boolean streaming)
       at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare)
       at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
       at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
       at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable)
       at WindowsFormsApplication2.Form1.InsertText(String docName, String SheetName0, String text, String CellRowRef0, UInt32 CellColRef0) in c:\dp13\General Application\WindowsFormsApplication9_4_0_1\WindowsFormsApplication2\Form1.cs:line 607
       at WindowsFormsApplication2.Form1.menuItem5_Click(Object sender, EventArgs e) in c:\dp13\General Application\WindowsFormsApplication9_4_0_1\WindowsFormsApplication2\Form1.cs:line 158
       at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
       at System.Windows.Forms.MenuItem.MenuItemData.Execute()
       at System.Windows.Forms.Command.Invoke()
       at System.Windows.Forms.Command.DispatchID(Int32 id)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsApplication2.Program.Main() in c:\dp13\General Application\WindowsFormsApplication9_4_0_1\WindowsFormsApplication2\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

 
due to last line below
                string Path0 = Folder0 + "\\New0.xlsx";

                            Boolean b = CreateSpreadsheetWorkbook(Path0, sheet.Name);

                                                InsertText(Path0, sheet.Name, cell.InnerText, Col0, Convert.ToUInt32(Row0));

        public static void InsertText(string docName, string SheetName0, string text, string CellRowRef0, uint CellColRef0)
        {
            using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            ...


and I expect to close relevant Excel file within InsertText. Is such way correct? If yes, how to close it within the event?

Many Thanks & Best Regards, Hua Min


how to programatically access built-in properties of open xml word doc?

$
0
0
i would like to display some built in properties of an open xml word doc file. i would like to use open xml sdk2.0 for this purpose. so i wonder if there is any class or any way i could programmatically access these builtin properties.

System.IO.FileFormatException on opening excel worksheet embedded in PowerPoint 2016 with OpenXml SDK

$
0
0

I have PPTX files generated by users with PowerPoint 2016. The slides have embedded excel worksheets which I need to access for further processing. I am using Open Xml SDK v2.6.1 in my project.

On passing the embedded object stream to the SpreadsheetDocument, using the following code:

using (PresentationDocument pd =PresentationDocument.Open(pptxFile,true)){foreach(SlidePart slide in pd.PresentationPart.GetPartsOfType<SlidePart>()){foreach(EmbeddedObjectPart eoPart in slide.EmbeddedObjectParts){
      using (SpreadsheetDocument sd =SpreadsheetDocument.Open(eoPart.GetStream(),true)){// do some work with worksheets                                var count = sd.WorkbookPart.WorksheetParts.Count();}}}}

I get the following exception:

System.IO.FileFormatException:File contains corrupted data.
at System.IO.Packaging.ZipPackage..ctor(Stream s,FileMode packageFileMode,FileAccess packageFileAccess)
at System.IO.Packaging.Package.Open(Stream stream,FileMode packageMode,FileAccess packageAccess)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(Stream stream,Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(Stream stream,Boolean isEditable,OpenSettings openSettings)
at...

When I open the pptx package and in the embeddings folder rename oleObject1.bin to oleObject1.zip, then see the file information in WinRar, I see that it is SFX Zip volume and not ZipArchive.

The only way I could get the SpreadsheetDocument to open the embedded object stream was to convert the stream to System.IO.Compression.ZipArchive using DotNetZip library.

So I have the following questions:

  1. Is there a way to get Open XML SDK to open embedded excel worksheet stream, without explicit transcoding (from SFX Zip volume to Zip Archive)?
  2. What is the best way to write the modified stream back into the presentation document? This is important because, the worksheet data will be updated and has to be written back to the host document.
  3. Is there another more elegant way to solve this issue?

Note: this issue does not occur when the worksheet is embedded programmatically using OpenXml SDK in the presentation.


Problem to refer to file

$
0
0

Hi,
I get

System.IO.IOException was unhandled
  HResult=-2146232800
  Message=Cannot modify a read-only container.
  Source=WindowsBase
  StackTrace:
       at System.IO.Packaging.Package.ThrowIfReadOnly()
       at System.IO.Packaging.Package.CreatePart(Uri partUri, String contentType, CompressionOption compressionOption)
       at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateMetroPart(Uri partUri, String contentType)
       at DocumentFormat.OpenXml.Packaging.OpenXmlPart.CreateInternal(OpenXmlPackage openXmlPackage, OpenXmlPart parent, String contentType, String targetExt)
       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 WindowsFormsApplication2.Form1.InsertWorksheet(WorkbookPart workbookPart) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 457
       at WindowsFormsApplication2.Form1.InsertText(SpreadsheetDocument spreadSheet, String SheetName0, String text, String CellRowRef0, UInt32 CellColRef0) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 626
       at WindowsFormsApplication2.Form1.menuItem5_Click(Object sender, EventArgs e) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 158
       at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
       at System.Windows.Forms.MenuItem.MenuItemData.Execute()
       at System.Windows.Forms.Command.Invoke()
       at System.Windows.Forms.Command.DispatchID(Int32 id)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsApplication2.Program.Main() in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
due to this line

            WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();


            
that is from 2nd event below. Why?
        public static void InsertText(SpreadsheetDocument spreadSheet, string SheetName0, string text, string CellRowRef0, uint CellColRef0)
        {
            //using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            // Open the document for editing.
            //Using(SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            //{
            // Get the SharedStringTablePart. If it does not exist, create a new one.
            SharedStringTablePart shareStringPart;
            if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
            {
                shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
            }
            else
            {
                shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
            }

            // Insert the text into the SharedStringTablePart.
            // int index = InsertSharedStringItem(text, shareStringPart);

            // Insert a new worksheet.
            WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart);

            // Insert cell A1 into the new worksheet.
            Cell cell = InsertCellInWorksheet(CellRowRef0, CellColRef0, worksheetPart);

            // Set the value of cell A1.
            cell.CellValue = new CellValue(text);
            cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);

            // Save the new worksheet.
            worksheetPart.Worksheet.Save();
            //}
        }
        private static WorksheetPart InsertWorksheet(WorkbookPart workbookPart)
        {
            // Add a new worksheet part to the workbook.
            WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
            newWorksheetPart.Worksheet.Save();

            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
            string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);

            // Get a unique ID for the new sheet.
            uint sheetId = 1;
            if (sheets.Elements<Sheet>().Count() > 0)
            {
                sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
            }

            string sheetName = "Sheet" + sheetId;

            // Append the new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
            sheets.Append(sheet);
            workbookPart.Workbook.Save();

            return newWorksheetPart;
        }


Many Thanks & Best Regards, Hua Min


Problem to slow process

$
0
0
Hi,
It is writely rather slowly into New0.xls by these codes. Where is the problem? I expect to COPY from onegiven Excel file into New0.xls.
                var ExcelObj = new Excel.Application();
                //Excel.Workbook Book0 = ExcelObj.Workbooks.Open(openFileDialog1.FileName, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true);
                ExcelObj.ScreenUpdating = false;

                Excel.Worksheet Worksheet0;
                string Folder0 = Path.GetDirectoryName(openFileDialog1.FileName);
                string Path0 = Folder0 + "\\New0.xlsx";
                string Col0 = "", Row0 = "";

                using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, true))
                    {
                        WorkbookPart workbookPart = doc.WorkbookPart;

                        /*Sheet theSheet = workbookPart.Workbook.Descendants<Sheet>().
                            Where(s => s.Name == "Sheet Overall").FirstOrDefault();*/
                        Sheet theSheet;

                        int sheetIndex = 0;
                        DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbookPart.Workbook.Sheets;
                        //foreach (WorksheetPart wsPart in workbookPart.WorksheetParts)
                        foreach (Sheet sheet in sheets)
                        {
                            //WorkbookStylesPart wstylePart = workbookPart.WorkbookStylesPart;
                            //Stylesheet ss = wstylePart.Stylesheet;
                            Boolean b = CreateSpreadsheetWorkbook(Path0, sheet.Name);
                            string sheetPartType = workbookPart.GetPartById(sheet.Id).GetType().Name;
                            using (StreamWriter sw = new StreamWriter(@File1, true, Encoding.Unicode))
                            {
                                sw.WriteLine("Sheet name is {0},Sheet ID is {1},sheetId is {2},sheetPartType is {3}", sheet.Name, sheet.Id, sheet.SheetId, sheetPartType);
                            }

                            if (sheetPartType != "WorksheetPart")
                            {
                                //Console.WriteLine("{0} is not a worksheet", sheet.Name);
                                using (StreamWriter sw = new StreamWriter(@File1, true, Encoding.Unicode))
                                {
                                    sw.WriteLine("{0} is not a worksheet", sheet.Name);
                                }
                            }
                            else
                            {
                                WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                                WorkbookStylesPart wstylePart = workbookPart.WorkbookStylesPart;
                                Stylesheet ss = wstylePart.Stylesheet;

                                foreach (Cell cell in worksheetPart.Worksheet.Descendants<Cell>())
                                {
                                    if (cell != null)
                                    {
                                        using (StreamWriter sw = new StreamWriter(@File1, true, Encoding.Unicode))
                                        {
                                            if (cell.DataType == null)
                                            {
                                                sw.WriteLine("Cell reference is {0}; Cell value is {1}", cell.CellReference, cell.InnerText);
                                                Col0 = ColumnPart(cell.CellReference); Row0 = RowPart(cell.CellReference);

                                                InsertText(doc, sheet.Name, cell.InnerText, Col0, Convert.ToUInt32(Row0));
                                            }
                                            else
                                            {
                                                switch (cell.DataType.Value)
                                                {
                                                    case CellValues.SharedString:

                                                        var stringTable =
                                                            workbookPart.GetPartsOfType<SharedStringTablePart>()
                                                            .FirstOrDefault();

                                                        if (stringTable != null)
                                                        {
                                                            sw.WriteLine("Cell reference is {0}; Cell value is {1}", cell.CellReference, stringTable.SharedStringTable.ElementAt(int.Parse(cell.InnerText)).InnerText);
                                                            Col0 = ColumnPart(cell.CellReference); Row0 = RowPart(cell.CellReference);
                                                            InsertText(doc, sheet.Name, cell.InnerText, Col0, Convert.ToUInt32(Row0));
                                                        }
                                                        break;
                                                }
                                            }
                                        }
                                    }
                                    ...
        public static void InsertText(SpreadsheetDocument spreadSheet, string SheetName0, string text, string CellRowRef0, uint CellColRef0)
        {
            //using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            // Open the document for editing.
            //Using(SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            //{
            // Get the SharedStringTablePart. If it does not exist, create a new one.
            SharedStringTablePart shareStringPart;
            if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
            {
                shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
            }
            else
            {
                shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
            }

            // Insert the text into the SharedStringTablePart.
            // int index = InsertSharedStringItem(text, shareStringPart);

            // Insert a new worksheet.
            WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart);

            // Insert cell A1 into the new worksheet.
            Cell cell = InsertCellInWorksheet(CellRowRef0, CellColRef0, worksheetPart);

            // Set the value of cell A1.
            cell.CellValue = new CellValue(text);
            cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);

            // Save the new worksheet.
            worksheetPart.Worksheet.Save();
            //}
        }

        // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
        // If the cell already exists, returns it.
        private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
        {
            DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = worksheetPart.Worksheet;
            SheetData sheetData = worksheet.GetFirstChild<SheetData>();
            string cellReference = columnName + rowIndex;

            // If the worksheet does not contain a row with the specified row index, insert one.
            Row row;
            if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
            {
                row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
            }
            else
            {
                row = new Row() { RowIndex = rowIndex };
                sheetData.Append(row);
            }

            // If there is not a cell with the specified column name, insert one.
            if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
            {
                return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
            }
            else
            {
                // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
                Cell refCell = null;
                foreach (Cell cell in row.Elements<Cell>())
                {
                    if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                    {
                        refCell = cell;
                        break;
                    }
                }

                Cell newCell = new Cell() { CellReference = cellReference };
                row.InsertBefore(newCell, refCell);

                worksheet.Save();
                return newCell;
            }
        }
        // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text
        // and inserts it into the SharedStringTablePart. If the item already exists, returns its index.
        private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
        {
            // If the part does not contain a SharedStringTable, create one.
            if (shareStringPart.SharedStringTable == null)
            {
                shareStringPart.SharedStringTable = new SharedStringTable();
            }

            int i = 0;

            // Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
            foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
            {
                if (item.InnerText == text)
                {
                    return i;
                }

                i++;
            }

            // The text does not exist in the part. Create the SharedStringItem and return its index.
            shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
            shareStringPart.SharedStringTable.Save();

            return i;
        }



Many Thanks & Best Regards, Hua Min



How to use openxml to get slide data by selection pane

$
0
0

Dear experts,

now i have a requirement to develop a translate powerpoint content.

I use OpenXML to extract the data from slide. But the result is all text in the slide.

is there any Class/API to get these text by its container which is in the powerpoint selection pane?

because i will write back the translated text to the same container.

Attach my current code, FYI:

public Dictionary<int,string> GetSlideIdAndText(string filePath, int index)
        {
            Dictionary<int, string> slideTexts = new Dictionary<int, string>();
            using (PresentationDocument ppt = PresentationDocument.Open(filePath, false))
            {
                // 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);

                // Get the inner text of the slide:
                IEnumerable<A.Text> texts = slide.Slide.Descendants<A.Text>();
                int i = 1;
                foreach (A.Text text in texts)
                {
                    slideTexts.Add(i,text.Text);
                    i++;
                }
            }
            return slideTexts;
        }
    }

Problem to open Excel file

$
0
0
Hi,
I expect to copy details from one given Excel file into another Excel file (called New0.xlsx) by these
                using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false))
                    {
                        using (FileStream fs1 = new FileStream(Path0, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            using (SpreadsheetDocument doc1 = SpreadsheetDocument.Open(fs1, false))
                            {
                                WorkbookPart workbookPart = doc.WorkbookPart;

                                /*Sheet theSheet = workbookPart.Workbook.Descendants<Sheet>().
                                    Where(s => s.Name == "Sheet Overall").FirstOrDefault();*/
                                Sheet theSheet;

                                int sheetIndex = 0;
                                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbookPart.Workbook.Sheets;
                                //foreach (WorksheetPart wsPart in workbookPart.WorksheetParts)
                                foreach (Sheet sheet in sheets)
                                {
                                    Boolean b = CreateSpreadsheetWorkbook(Path0, sheet.Name);
                                    ...



but how to resolve this problem
System.IO.FileNotFoundException was unhandled
  HResult=-2147024894
  Message=Could not find file 'C:\dp13\New0.xlsx'.
  Source=mscorlib
  FileName=C:\dp13\New0.xlsx
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
       at WindowsFormsApplication2.Form1.menuItem5_Click(Object sender, EventArgs e) in c:\dp13\General Application\WindowsFormsApplication9_4_0_3\WindowsFormsApplication2\Form1.cs:line 97
       at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
       at System.Windows.Forms.MenuItem.MenuItemData.Execute()
       at System.Windows.Forms.Command.Invoke()
       at System.Windows.Forms.Command.DispatchID(Int32 id)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsApplication2.Program.Main() in c:\dp13\General Application\WindowsFormsApplication9_4_0_3\WindowsFormsApplication2\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:


due to this line

using (FileStream fs1 = new FileStream(Path0, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))



Many Thanks & Best Regards, Hua Min


TextWrappingValues

$
0
0

Hello,

How do I set the TextWrappingValue to Around in my C# open xml file.

TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
                TableLook tableLook = new TableLook() { Val = "04A0" };
                TextWrappingValues tableTextWrapping = TextWrappingValues.Around;
                tableProperties.Append(tableTextWrapping);

I get the following error on the append:
cannot convert from ‘DocumentFormat.OpenXml.Wordprocessing.TextWrappingValues’ to ‘System.Collections.Generic.IEnumerable<DocumentFormat.OpenXml.OpenXmlElement>’

Thanks,

KS


keith

Problem to ObjectDisposedException

$
0
0
Hi,
I get
System.ObjectDisposedException was unhandled
  HResult=-2146232798
  Message=Cannot access a disposed object. Object name: 'SpreadsheetDocument'  Source=DocumentFormat.OpenXml
  ObjectName=SpreadsheetDocument
  StackTrace:
       at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.ThrowIfObjectDisposed()
       at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.GetSubPartOfType[T]()
       at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.get_WorkbookPart()
       at WindowsFormsApplication2.Form1.InsertText(SpreadsheetDocument spreadSheet, String SheetName0, String text, String CellRowRef0, UInt32 CellColRef0) in c:\dp13\General Application\WindowsFormsApplication9_4_0_4\WindowsFormsApplication2\Form1.cs:line 659
       at WindowsFormsApplication2.Form1.menuItem5_Click(Object sender, EventArgs e) in c:\dp13\General Application\WindowsFormsApplication9_4_0_4\WindowsFormsApplication2\Form1.cs:line 198
       at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
       at System.Windows.Forms.MenuItem.MenuItemData.Execute()
       at System.Windows.Forms.Command.Invoke()
       at System.Windows.Forms.Command.DispatchID(Int32 id)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsApplication2.Program.Main() in c:\dp13\General Application\WindowsFormsApplication9_4_0_4\WindowsFormsApplication2\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 



due to this line
            if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)



below. How to use IsDisposed property to avoid this problem?

        public static void InsertText(SpreadsheetDocument spreadSheet, string SheetName0, string text, string CellRowRef0, uint CellColRef0)
        {
            //using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            // Open the document for editing.
            //Using(SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            //{
            // Get the SharedStringTablePart. If it does not exist, create a new one.
            SharedStringTablePart shareStringPart;
            if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
            {
                shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
            }
            else
            {
                shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
            }



Many Thanks & Best Regards, Hua Min

Excel Workbook Data Refresh using OpenXML

$
0
0

Hi,

I need to automate the Excel Workbook Data Refresh(Source and Pivot table). Can we do this using OpenXML SDK?

I am using VB Script to Refresh the Workbook but this needs excel software in order to open the workbook and do the refresh.

So I am looking for the approach which does not need Excel to be installed to automate the refresh.

Regards,

Vidya Lokesh

Different part name between Excel and Open-XML-SDK

$
0
0

When I call the function WorksheetPart.AddNewPart<DrawingsPart>, the result part filename is /xl/drawings/drawing.xml, which is different from what Excel 2013 names it (/xl/drawings/drawing1.xml). Note the "1". This wouldn't matter, except that the Open XML SDK 2.5 Productivity Tool for Microsoft Office won't compare DrawingsPart s created the two different ways.

What's causing this is that line 7719 of DocumentFormat.OpenXml\src\GeneratedCode\package.cs returns the TargetNameConstant which lacks the "1":
internal const System.String TargetNameConstant =@"drawing";

There's a similar issue for part /xl/worksheets/sheet1.xml on lines 9891 & 9897 of the same package.cs file:
internal const System.String TargetNameConstant =@"sheet";

I need to control the name of the DrawingsPart so the Productivity Tool can generate Open-XML-SDK code for me to use in my program. Can you help me? If this requires a change to the Productivity Tool, I have other ideas for enhancements too.

Howard Rubin

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()


How can I get table column actual width from xml excel 2003?

$
0
0

I need read column width and row height from xml excel 2003 for printing.But I found that is no law.

Fox example:

    Open a xls file and set columns width 1mm、2mm、3mm、4mm、5mm.Then file save as  xml excel 2003.Open xml file,the value of  columns were 9.6、15、23.4、25.8、31.2.It is no law.

    How can I get table column actual width from xml excel 2003?

Powerpoint needs to be repaired issues

$
0
0

Hi everyone,

I have a powerpoint file that needs to be repaired each time I try to open it. I have saved a copy of the repaired version and have tried to make the xml exactly the same however powerpoint still wants to repair it. The open XML validator reports no issues. Is there any way to see why powerpoint doesn't like a file? Does the formatting of the XML matter e.g carriage return? 

Many thanks,

Lakhvir


Save chart as image by using Open XML

$
0
0

create an Excel file in .NET using OpenXML and Draw chart. How to save this chart as image.

Thanks in advacen

Fill Picture content control in header of word doc using OpenXML

$
0
0

Hi,

I want to fill my Picture Content Control that is located in the headerof my word document with this code: (I have passed content control tag and the image stream via document parameter to this function)

       public void FillDocument(Stream stream, XDocument document)
        {                

using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(stream, true))
            {
                List<SdtElement> descendants = wordDocument.MainDocumentPart.Document.Descendants<SdtElement>().ToList();

foreach (var headerPart in wordDocument.MainDocumentPart.HeaderParts)
                {
                    descendants.AddRange(headerPart.Header.Descendants<SdtElement>().ToList());
                }
                foreach (var footerPart in wordDocument.MainDocumentPart.FooterParts)
                {
                    descendants.AddRange(footerPart.Footer.Descendants<SdtElement>().ToList());
                }

                XDocument doc = document;

                foreach (SdtElement item in descendants)
                {
                    SdtAlias alias = item.Descendants<SdtAlias>().FirstOrDefault();

                    if (alias != null)
                    {                         
                        string sdtTitle = alias.Val.Value;


                        //if Sdt Content Control is Picture
                        string imageContent = (from xElement in doc.Descendants("Picture") where xElement.Attribute("Id").Value == sdtTitle select xElement.Value).FirstOrDefault();
                        if (imageContent != null)
                        {
                            MemoryStream result = (MemoryStream)StringToStream(imageContent);

                            SdtProperties p = item.Elements<SdtProperties>().FirstOrDefault();
                            if (p != null)
                            {
                                // Is it a picture content control?
                                SdtContentPicture pict = p.Elements<SdtContentPicture>().FirstOrDefault();
                                // Get the alias.
                                SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();
                                if (pict != null && a.Val.Value == sdtTitle)
                                {
                                    string embed = null;
                                    Drawing dr = item.Descendants<Drawing>().FirstOrDefault();
                                    if (dr != null)
                                    {
                                        D.Blip blip = dr.Descendants<D.Blip>().FirstOrDefault();
                                        if (blip != null)
                                            embed = blip.Embed;
                                        if (embed != null)
                                        {
                                            IdPartPair idpp = wordDocument.MainDocumentPart.Parts
                                                .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                                            if (idpp != null)
                                            {
                                                ImagePart ip = (ImagePart)idpp.OpenXmlPart;
                                                ip.FeedData(result);
                                            }
                                        }
                                    }
                                }
                            }



                            continue;
                        }

}

}

It finds the Pictire content control in word document but in this line:

 ImagePart ip = (ImagePart)idpp.OpenXmlPart;

I get this error:

Unable to cast object of type ‘DocumentFormat.OpenXml.Packaging.CustomXmlPart’ to type ‘DocumentFormat.OpenXml.Packaging.ImagePart’.

Could you please guide me?






Problem to cell's data type

$
0
0
Hi,
I want to know why I get nothing to cell's Data type, using these
                                WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                                WorkbookStylesPart wstylePart = workbookPart.WorkbookStylesPart;
                                Stylesheet ss = wstylePart.Stylesheet;

                                foreach (Cell cell in worksheetPart.Worksheet.Descendants<Cell>())
                                {
                                    if (cell != null)
                                    {
                                        using (StreamWriter sw = new StreamWriter(@File1, true, Encoding.Unicode))
                                        {
                                            if (cell.DataType == null)
                                                sw.WriteLine("Cell reference is {0}; Cell value is {1}", cell.CellReference, cell.InnerText);
                                            else
                                            {
                                                switch (cell.DataType.Value)
                                                {
                                                    case CellValues.SharedString:

                                                        var stringTable =
                                                            workbookPart.GetPartsOfType<SharedStringTablePart>()
                                                            .FirstOrDefault();

                                                        if (stringTable != null)
                                                        {
                                                            sw.WriteLine("Cell reference is {0}; Data type of Cell is {1}", cell.CellReference, cell.DataType);
                                                        }
                                                        break;
                                                }
                                            }
                                        }
                                    }


when the cell is having a number inside.

Many Thanks & Best Regards, Hua Min

Update to cell's properties

$
0
0
Hi,
I want to write to Excel cell with value, by also putting exact values to such properties

font.Color.Rgb.Value
font.Color.Theme.Value

is there an example to this?

Many Thanks & Best Regards, Hua Min

Where do i have to store a Custom SmartArt Color (.gcsx) or a Custom SmartArt QuickStyle (.gqsx)

$
0
0

Hello

I created a Custom SmartArt Layout (.glox), Custom SmartArt Color (.gcsx) or a Custom SmartArt QuickStyle (.gqsx).

Discribed on:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/c4f15db4-90bb-447d-8dd6-bb0afadd218c/smartart-creating-custom-smartart-that-works-with-pictures?forum=officegeneral

I copied them in the Folder: "%APPDATA%\Microsoft\Templates\SmartArt Graphics"

But when i open "Microsoft PowerPoint 2016" (Windows) i see only the Custom SmartArt Layout (.glox).

Is the directory "%APPDATA%\Microsoft\Templates\SmartArt Graphics" correct for the GCSX- and GQSX-File or do i have to store then in an other Directory?

Thanks for your attention.





Viewing all 1288 articles
Browse latest View live


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