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

IENumerable to Generic List

$
0
0

Hi folks,

I have had some excellent guidance to date and could use a bit of guidance on how to get an IeNumerable to a generic list to be passed into a function with the following root requirement... Read CSV (looking at either CSVHelper or LinqtoCSV or a better option if proposed) Parse data and send result to Function that inserts the content to an existing Word Table identified by a BookMark.

Thanks In Advance for any assistance.

Code I have to date is below. Please Advise.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LINQtoCSV;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace CSVWorkCSharp
{
    class Program
    {
        public static void OpenAndAddTextToWordDocument(string FilePath, string BookMarkNameToModify, List<string[]> TableData)
        {
            // Open a WordprocessingDocument for editing using the file path.
            WordprocessingDocument wordDoc =
                WordprocessingDocument.Open(FilePath, true);
            //marker for main document part
            var mainDocPart = wordDoc.MainDocumentPart;
            //load bookmarks
            var bookmarks = mainDocPart.Document.Body.Descendants<BookmarkStart>();
            //find our bookmark
            var bookmark =
                from bookmarkIndex in bookmarks
                where bookmarkIndex.Name == BookMarkNameToModify
                select bookmarkIndex;
            //get to first element
            OpenXmlElement elem = bookmark.First().Parent;
            //isolate the table to be worked on
            while (!(elem is DocumentFormat.OpenXml.Wordprocessing.Table))
                elem = elem.Parent;
            var foundOurTable = elem;//FOUND THE TABLE
            //save the row you want to copy each time you have data
            var oldRow = elem.Elements<TableRow>().Last();
            DocumentFormat.OpenXml.Wordprocessing.TableRow row = (TableRow)oldRow.Clone();
            //whack old row
            elem.RemoveChild<TableRow>(oldRow);
            //Time to slap our data into the table
            foreach (String[] item in TableData)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableRow newRow = (TableRow)row.Clone();
                var cells = newRow.Elements<DocumentFormat.OpenXml.Wordprocessing.TableCell>();
                //BE SURE YOU HAVE RIGHT DATA COUNT PER ROW BEFORE DOING THIS!!
                for (int i = 0;
                    i < cells.Count();
                    i++)
                {
                    var c = cells.ElementAt(i);
                    var run = c.Elements<Paragraph>().First().Elements<Run>().First();
                    var text = run.Elements<Text>().First();
                    text.Text = item[i];
                }
                foundOurTable.AppendChild(newRow);
            }
            /*Close the handle explicitly.*/
            mainDocPart.Document.Save();
            wordDoc.Close();
        }
        static void Main(string[] args)
        {
            //Set Options for the CSV Import 'inputFileDescription' for use with the defined CSV context 'cc'
            CsvFileDescription inputFileDescription = new CsvFileDescription
            {
                SeparatorChar = ',',
                FirstLineHasColumnNames = true
            };
            //Create CSV Context 'cc' for reading and writing CSVs
            CsvContext cc = new CsvContext();
            IEnumerable<jobsummary> retrievejobsSummary=
                cc.Read<jobsummary>(@"D:\ScriptData\newmasterdata\jobs\bpdbjobs_summary.csv", inputFileDescription);
            var sjobtype =
                from items in retrievejobsSummary
                where items.JobType != "Image_Cleanup" && items.jobs_kb > 1000 && items.jobs_Elapsed>20000
                orderby items.JobID,items.jobs_Start_Time
                select new { items.JobID, items.jobs_kb, items.jobs_Elapsed};   
            var sumelapsed=
                from p in retrievejobsSummary
                where p.JobType != "Active" && p.jobs_kb > 800
                orderby p.JobID
                group p by p.GetType() into g
                select new{ Prop=g.Key,Backup_Duration=g.Sum(p=>p.jobs_Elapsed),BackedUpSizeKB=g.Sum(p=>p.jobs_kb)};
            Console.WriteLine("Job ID\t\tDuration\tSize");
            foreach (var item in sjobtype)
            {
                Console.WriteLine("{0}\t\t{1}\t\t{2}", item.JobID,item.jobs_Elapsed,item.jobs_kb);
            }
            Console.WriteLine();
            foreach (var items in sumelapsed)
            {
                Console.WriteLine("{0}\t{1}", items.Backup_Duration, items.BackedUpSizeKB);
            }
            //Word Template Containing Bookmarks
			const string file = @"D:\ScriptData\This is a Test.dotx";
			/*GOAL is to PASS SJOBTYPE to the function so that it can be inserted 
			  at the bookmark(appending to the existing table*/
			OpenAndAddTextToWordDocument(file, "JobSummaryTableAttempt1", sjobtype.ToList());







            //foreach (var item in sumelapsed) {
            //    Console.WriteLine("Total Elapsed Time:{0} minutes    Total Size of Backups: {1}",
            //        item.Backup_Duration,item.BackedUpSizeKB); }
            //Console.WriteLine(sumelapsed);
            Console.ReadKey();
        }
    }
}


Power Point. Creating presentation. Adding image and table.

$
0
0

Hello!

I need to add image to first slide, and add table 4x4 with random data to second slide.

I have this code: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using P = DocumentFormat.OpenXml.Presentation;
using D = DocumentFormat.OpenXml.Drawing;

namespace CreatePPTFile
{
    class PresentClass
    {
        public static void CreatePresentation(string filepath)
        {
            // Create a presentation at a specified file path. The presentation document type is pptx, by default.
            PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation);
            PresentationPart presentationPart = presentationDoc.AddPresentationPart();
            presentationPart.Presentation = new Presentation();

            CreatePresentationParts(presentationPart);

            // Close the presentation handle
            presentationDoc.Close();
        }

        private static void CreatePresentationParts(PresentationPart presentationPart)
        {
            SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" });
            SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" });
            SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 };
            NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 };
            DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle();

            presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1);

            SlidePart slidePart1;
            SlideLayoutPart slideLayoutPart1;
            SlideMasterPart slideMasterPart1;
            ThemePart themePart1;


            slidePart1 = CreateSlidePart(presentationPart);
            slideLayoutPart1 = CreateSlideLayoutPart(slidePart1);
            slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1);
            themePart1 = CreateTheme(slideMasterPart1);

            slideMasterPart1.AddPart(slideLayoutPart1, "rId1");
            presentationPart.AddPart(slideMasterPart1, "rId1");
            presentationPart.AddPart(themePart1, "rId5");
        }

        private static SlidePart CreateSlidePart(PresentationPart presentationPart)
        {
            SlidePart slidePart1 = presentationPart.AddNewPart<SlidePart>("rId2");
            slidePart1.Slide = new Slide(
                    new CommonSlideData(
                        new ShapeTree(
                            new P.NonVisualGroupShapeProperties(
                                new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
                                new P.NonVisualGroupShapeDrawingProperties(),
                                new ApplicationNonVisualDrawingProperties()),
                            new GroupShapeProperties(new TransformGroup()),
                            new P.Shape(
                                new P.NonVisualShapeProperties(
                                    new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" },
                                    new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
                                    new ApplicationNonVisualDrawingProperties(new PlaceholderShape())),
                                new P.ShapeProperties(),
                                new P.TextBody(
                                    new BodyProperties(),
                                    new ListStyle(),
                                    new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))))),
                    new ColorMapOverride(new MasterColorMapping()));
            return slidePart1;
        }

        private static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1)
        {
            SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart<SlideLayoutPart>("rId1");
            SlideLayout slideLayout = new SlideLayout(
            new CommonSlideData(new ShapeTree(
              new P.NonVisualGroupShapeProperties(
              new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
              new P.NonVisualGroupShapeDrawingProperties(),
              new ApplicationNonVisualDrawingProperties()),
              new GroupShapeProperties(new TransformGroup()),
              new P.Shape(
              new P.NonVisualShapeProperties(
                new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" },
                new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
                new ApplicationNonVisualDrawingProperties(new PlaceholderShape())),
              new P.ShapeProperties(),
              new P.TextBody(
                new BodyProperties(),
                new ListStyle(),
                new Paragraph(new EndParagraphRunProperties()))))),
            new ColorMapOverride(new MasterColorMapping()));
            slideLayoutPart1.SlideLayout = slideLayout;
            return slideLayoutPart1;
        }

        private static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1)
        {
            SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart<SlideMasterPart>("rId1");
            SlideMaster slideMaster = new SlideMaster(
            new CommonSlideData(new ShapeTree(
              new P.NonVisualGroupShapeProperties(
              new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
              new P.NonVisualGroupShapeDrawingProperties(),
              new ApplicationNonVisualDrawingProperties()),
              new GroupShapeProperties(new TransformGroup()),
              new P.Shape(
              new P.NonVisualShapeProperties(
                new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" },
                new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
                new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })),
              new P.ShapeProperties(),
              new P.TextBody(
                new BodyProperties(),
                new ListStyle(),
                new Paragraph())))),
            new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1,
                Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2,
                Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2,
                Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4,
                Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6,
                Hyperlink = D.ColorSchemeIndexValues.Hyperlink,
                FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink },
                new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }),
                new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle()));
            slideMasterPart1.SlideMaster = slideMaster;

            return slideMasterPart1;
        }

        private static ThemePart CreateTheme(SlideMasterPart slideMasterPart1)
        {
            ThemePart themePart1 = slideMasterPart1.AddNewPart<ThemePart>("rId5");
            D.Theme theme1 = new D.Theme() { Name = "Office Theme" };

            D.ThemeElements themeElements1 = new D.ThemeElements(
            new D.ColorScheme(
              new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }),
              new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }),
              new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }),
              new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }),
              new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }),
              new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }),
              new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }),
              new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }),
              new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }),
              new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }),
              new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }),
              new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) { Name = "Office" },
              new D.FontScheme(
              new D.MajorFont(
              new D.LatinFont() { Typeface = "Calibri" },
              new D.EastAsianFont() { Typeface = "" },
              new D.ComplexScriptFont() { Typeface = "" }),
              new D.MinorFont(
              new D.LatinFont() { Typeface = "Calibri" },
              new D.EastAsianFont() { Typeface = "" },
              new D.ComplexScriptFont() { Typeface = "" })) { Name = "Office" },
              new D.FormatScheme(
              new D.FillStyleList(
              new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
              new D.GradientFill(
                new D.GradientStopList(
                new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 },
                  new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
                new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 },
                 new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 35000 },
                new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 },
                 new D.SaturationModulation() { Val = 350000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 100000 }
                ),
                new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
              new D.NoFill(),
              new D.PatternFill(),
              new D.GroupFill()),
              new D.LineStyleList(
              new D.Outline(
                new D.SolidFill(
                new D.SchemeColor(
                  new D.Shade() { Val = 95000 },
                  new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
                new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
              {
                  Width = 9525,
                  CapType = D.LineCapValues.Flat,
                  CompoundLineType = D.CompoundLineValues.Single,
                  Alignment = D.PenAlignmentValues.Center
              },
              new D.Outline(
                new D.SolidFill(
                new D.SchemeColor(
                  new D.Shade() { Val = 95000 },
                  new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
                new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
              {
                  Width = 9525,
                  CapType = D.LineCapValues.Flat,
                  CompoundLineType = D.CompoundLineValues.Single,
                  Alignment = D.PenAlignmentValues.Center
              },
              new D.Outline(
                new D.SolidFill(
                new D.SchemeColor(
                  new D.Shade() { Val = 95000 },
                  new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
                new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
              {
                  Width = 9525,
                  CapType = D.LineCapValues.Flat,
                  CompoundLineType = D.CompoundLineValues.Single,
                  Alignment = D.PenAlignmentValues.Center
              }),
              new D.EffectStyleList(
              new D.EffectStyle(
                new D.EffectList(
                new D.OuterShadow(
                  new D.RgbColorModelHex(
                  new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
              new D.EffectStyle(
                new D.EffectList(
                new D.OuterShadow(
                  new D.RgbColorModelHex(
                  new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
              new D.EffectStyle(
                new D.EffectList(
                new D.OuterShadow(
                  new D.RgbColorModelHex(
                  new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))),
              new D.BackgroundFillStyleList(
              new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
              new D.GradientFill(
                new D.GradientStopList(
                new D.GradientStop(
                  new D.SchemeColor(new D.Tint() { Val = 50000 },
                    new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
                new D.GradientStop(
                  new D.SchemeColor(new D.Tint() { Val = 50000 },
                    new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
                new D.GradientStop(
                  new D.SchemeColor(new D.Tint() { Val = 50000 },
                    new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
                new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
              new D.GradientFill(
                new D.GradientStopList(
                new D.GradientStop(
                  new D.SchemeColor(new D.Tint() { Val = 50000 },
                    new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
                new D.GradientStop(
                  new D.SchemeColor(new D.Tint() { Val = 50000 },
                    new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
                new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) { Name = "Office" });

            theme1.Append(themeElements1);
            theme1.Append(new D.ObjectDefaults());
            theme1.Append(new D.ExtraColorSchemeList());

            themePart1.Theme = theme1;
            return themePart1;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;

namespace CreatePPTFile
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            addDataToDGV(dgv);
            pictureLocantionTxtB.Text = Application.StartupPath + "\\sample.jpg";
        }

        //Filling dataGridView
        private void addDataToDGV(DataGridView dgv)
        {
            Random r = new Random();
            for (int i = 0; i < 4; i++)
            {
                dgv.Rows.Add(randomChar(r), randomChar(r),
                            randomChar(r), randomChar(r));
            }
        }

        //Getting random char
        private char randomChar(Random r)
        {
            return (char)('a' + r.Next(27));
        }

        //Selecting picture for inserting to presentation
        private void pictureSelectBtn_Click(object sender, EventArgs e)
        {
            ofd.Filter = "All pictures|*.jpg;*.jpeg;*.png;";
            ofd.FileName = "";
            ofd.ShowDialog();
            pictureLocantionTxtB.Text = ofd.FileName;
        }

        private void CreatePPTBtn_Click(object sender, EventArgs e)
        {
            sfd.FileName = "example";
            sfd.DefaultExt = ".pptx";
            sfd.Filter = "Power Point file (*.pptx)|*.pptx";
            sfd.ShowDialog();
            string outputfilename = sfd.FileName;

            PresentClass.CreatePresentation(outputfilename);

            if (outputfilename != "")
            {
                //string pptFilePath = outputfilename.Trim();
                string pptFilePath = textBox1.Text.Trim();
                string imagefilePath = pictureLocantionTxtB.Text.Trim();
                string imageExt = Path.GetExtension(imagefilePath);
                if ((imageExt.Equals("jpg", StringComparison.OrdinalIgnoreCase))
                    || (imageExt.Equals("jpeg", StringComparison.OrdinalIgnoreCase)))
                {
                    imageExt = "image/jpeg";
                }
                else
                {
                    imageExt = "image/png";
                }

                bool condition = string.IsNullOrEmpty(pptFilePath)
                    || !File.Exists(pptFilePath)
                    || string.IsNullOrEmpty(imagefilePath)
                    || !File.Exists(imagefilePath);
                if (condition)
                {
                    MessageBox.Show("The PowerPoint or iamge file is invalid,Please select an existing file again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true))
                    {
                        // Get the presentation Part of the presentation document
                        PresentationPart presentationPart = presentationDocument.PresentationPart;
                        presentationDocument.PresentationPart.Presentation.Save();
                        MessageBox.Show("Insert Image Successfully,you can check with opening PowerPoint");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                //MessageBox.Show("Presentation has been created sucessfully" +
                //    Environment.NewLine + "Please find the presentation at " + outputfilename);
            }
        }
    }
}

Can you help me please ?

Thanks in Advance

Validation of Powerpoint presentations

$
0
0

Hi

We have a webservice creating Office documents using Open XML SDK developed in VS 2010.

We run into problems when creating Powerpoint-presentations in some scenarios.
We create the presentation using another pre-created presentation on which we apply the SlideMaster from a template presentation. In most cases this works fine and the presentations opens nicely in Powerpoint.
The strange thing is that with certain combination of pre-created presentation and template presentation, the resulting file doesn't open in Powerpoint without asking for repair.

Now, when we use Open XML Productivity tool to validate the file, the validation result only consists if the "smtclean is not declared" messages, which seems to be shown for every type of presentation you try to validate, even a new blank presentation created with Powerpoint.
Nothing wrong is found in validation which can explain the repair-message in Powerpoint.

If we repair the presentation, save it and use the comparison tool, there are a lot of differences, but they all seem to be of the "renaming sort" if slidelayout parts. Why isn't the validating tools show me whats actually wrong?

The following code is used to apply the SlideMaster to the pre-created presentation:

    Private Sub PTUpdateFormats(ByVal themeFile As String, ByVal presFile As String)

        Using themeDocument As PresentationDocument = PresentationDocument.Open(themeFile, False)
            Using presentationDocument As PresentationDocument = presentationDocument.Open(presFile, True)
                PTApplyTheme(presentationDocument, themeDocument)
            End Using
        End Using

    End Sub

    Public Sub PTApplyTheme(ByVal presentationDocument As PresentationDocument, ByVal themeDocument As PresentationDocument)

        If (presentationDocument Is Nothing) Then
            Throw New ArgumentNullException("presentationDocument")
        End If
        If (themeDocument Is Nothing) Then
            Throw New ArgumentNullException("themeDocument")
        End If

        ' Get the presentation part of the presentation document.
        Dim presentationPart As PresentationPart = presentationDocument.PresentationPart

        ' Get the existing slide master part.
        Dim slideMasterPart As SlideMasterPart = presentationPart.SlideMasterParts.ElementAt(0)

        ' Get id for the existing slide master part.
        Dim relationshipId As String = presentationPart.GetIdOfPart(slideMasterPart)

        ' Get the new slide master part.
        Dim newSlideMasterPart As SlideMasterPart = themeDocument.PresentationPart.SlideMasterParts.ElementAt(0)

        ' Remove the theme part.
        presentationPart.DeletePart(presentationPart.ThemePart)

        ' Remove the old slide master part.
        presentationPart.DeletePart(slideMasterPart)

        ' Import the new slide master part, and reuse the old relationship ID.
        newSlideMasterPart = presentationPart.AddPart(newSlideMasterPart, relationshipId)

        ' Change to the new theme part.
        presentationPart.AddPart(newSlideMasterPart.ThemePart)
        Dim newSlideLayouts As Dictionary(Of String, SlideLayoutPart) = New Dictionary(Of String, SlideLayoutPart)()
        For Each slideLayoutPart As Object In newSlideMasterPart.SlideLayoutParts
            newSlideLayouts.Add(GetSlideLayoutType(slideLayoutPart), slideLayoutPart)
        Next
        Dim layoutType As String = Nothing
        Dim newLayoutPart As SlideLayoutPart = Nothing

        ' Insert the code for the layout for this example.
        Dim defaultLayoutType As String = "Rubrik och innehåll"

        ' Remove the slide layout relationship on all slides.
        For Each slidePart As SlidePart In presentationPart.SlideParts
            layoutType = Nothing
            If (Not (slidePart.SlideLayoutPart) Is Nothing) Then

                ' Determine the slide layout type for each slide.
                layoutType = GetSlideLayoutType(slidePart.SlideLayoutPart)

                ' Delete the old layout part.
                slidePart.DeletePart(slidePart.SlideLayoutPart)
            End If

            If ((Not (layoutType) Is Nothing) AndAlso newSlideLayouts.TryGetValue(layoutType, newLayoutPart)) Then
                ' Apply the new layout part.
                slidePart.AddPart(newLayoutPart)
            Else
            	newLayoutPart = newSlideLayouts(defaultLayoutType)
            	' Apply the new default layout part.
            	slidePart.AddPart(newLayoutPart)
            End If
        Next

    End Sub

    ' Get the type of the slide layout.
    Public Function GetSlideLayoutType(ByVal slideLayoutPart As SlideLayoutPart) As String
        Dim slideData As CommonSlideData = slideLayoutPart.SlideLayout.CommonSlideData
        ' Remarks: If this is used in production code, check for a null reference.
        Return slideData.Name

    End Function

If anybody would like to test with my sample files, they can be downloaded from Skydrive files (Powerpoint files.zip)

Is there anything wrong with my code, or am I missing to check something when I merge the Slidemaster to the presentation?
A lot of other pre-created presentations and templates works fine to merge, but the combination that can be downloaded above won't work. Actually, the template and the pre-created presentation works together with other files.

Thanks in advance


Best Regards Peter Karlström Midrange AB, Sweden


How to optimize Excel export with Open XML?

$
0
0

Hello,

I want to optimize my Excel data export, done with Open XML. I need to export more than 100.000 rows with about 30 columns.

Here you have my code (data from datatable). It's very slow. Any idea to optimize? Thanks.

Dim newRow As New Row()

Dim iIndexCol As Integer = 1

For Each row As DataRow In dt.Rows

    iRow = iRow + 1

    newRow = New Row()

    Dim oCellData As Cell = New Cell()

    For Each col As DataColumn In dt.Columns

        oCellData = New Cell()

        If (iIndexCol = 6 Or iIndexCol = 7 Or iIndexCol = 15 Or iIndexCol = 36) Then    'fechas

            oCellData.DataType = CellValues.String

            oCellData.StyleIndex = 1

            oCellData.CellValue = New CellValue(RTrim(IIf(IsDBNull(row(col.ColumnName)), "", row(col.ColumnName).ToString().Substring(0, 10))))

        ElseIf (iIndexCol = 17) Then '8 decimales

            oCellData.DataType = CellValues.Number

            oCellData.StyleIndex = 5

            oCellData.CellValue = New CellValue(Replace(RTrim(IIf(IsDBNull(row(col.ColumnName)), "", row(col.ColumnName).ToString())), ",", "."))

        ElseIf (iIndexCol = 10) Then '6 decimales

            oCellData.DataType = CellValues.Number

            oCellData.StyleIndex = 3

            oCellData.CellValue = New CellValue(Replace(RTrim(IIf(IsDBNull(row(col.ColumnName)), "", row(col.ColumnName).ToString())), ",", "."))

            '2 decimales

        ElseIf (iIndexCol >= 11 And iIndexCol <= 13) Or (iIndexCol >= 17 And iIndexCol <= 19) Or (iIndexCol >= 22 And iIndexCol <= 25) Or (iIndexCol >= 32 And iIndexCol <= 35) Then

            oCellData.DataType = CellValues.Number

            oCellData.StyleIndex = 4

            oCellData.CellValue = New CellValue(Replace(RTrim(IIf(IsDBNull(row(col.ColumnName)), "", row(col.ColumnName).ToString())), ",", "."))

        Else

            oCellData.DataType = CellValues.String

            oCellData.StyleIndex = 0

            oCellData.CellValue = New CellValue(RTrim(IIf(IsDBNull(row(col.ColumnName)), "", row(col.ColumnName).ToString())))

        End If

        newRow.AppendChild(oCellData)

        iIndexCol = iIndexCol + 1

    Next

    iIndexCol = 1

    newRow.RowIndex = iRow

    oSheetData.AppendChild(newRow)

Next

How to add an image to a word processing document using SXLT.

$
0
0

I am using an .xslt file to generate a docx file. I have a link of a picture in sxlt which can be found by using <xsl:value-of select="pic"/>. I used this value and successfully generated picture in a html table. There I used code like 

    <img>
           <xsl:attribute name="src"><xsl:value-of select="pic"/></xsl:attribute>
           <xsl:attribute name="type"><xsl:value-of select="concat('data:image/gif;base64,',xPath)"/></xsl:attribute>
           </img>

Now I want to show the image in a docx file which is generated using wordprocessingml. Any help or suggestions would be much appreciated.

-Nahid Shah

why is previous data from an xml file still populating Content Controls?

$
0
0

Hoping someone can help this newbie.

I have a program that allows me to create the fields which will allow me to collect data which I can export as xml. 

I have a Word 2007 dotx which I have 200 - 300 content controls which I have mapped to the xml file using '2007 Content Control Toolkit'. I run the word template and all is fine - data appears where I'd expect. This completes a report for my customers.

I then collect new data and export in xml. I have read how to change the word.dotx to a zip file, and replace the 'item1.xml' with my new xml file which I have also named 'item1.xml'. 

I then run the dotx and find it has become a mish-mash of both old and new data in the content control spaces. It seems to update/over-write if I have new data, but if there was no new data collected in some fields (they were left blank for example), the old data remains behind.

Can anyone suggest what I can do? It seems I have either more work to do than simply replacing the existing 'item1.xml' file or I need to be able to 'flush' away the previous data before applying the new 'item1.xml'.

Any help would be greatly appreciated, thank you.

Open XML

$
0
0

Hi All,

I have developed a word document which does some drawing on  run time using openXML SDK's .dll

My question here is can this word document be opened on a client machine where in Microsoft Office/word is not installed ?

How to change the header and footer in the Section Breaks Next Page using OpenXML?

$
0
0

I have a word document file in which I added a Section Break of Next Page, now I want to change the header and footer of that page.

Scenario of example, I have a doc file which has four pages with headers and footers and added fifth page in the section break next page, I want to change the header and footer of the fifth page only. This is achievable manually by deselecting the Link to Previous button in the Word Application but I don't know how to change it using XML?

My code that adds the new page in the section breaks is:

class Program
	{
		static void Main(string[] args)
		{
			string path = @"C:\Riyaz\sample.docx";
			string strtxt = "Hello This is done by programmatically";      
		   OpenAndAddTextToWordDocument(path,strtxt);
		}
		public static void OpenAndAddTextToWordDocument(string filepath, string txt)
		{
			using (DocX document = DocX.Load(@"C:\Riyaz\sample.docx"))
			{            
				document.InsertSectionPageBreak();
				Paragraph p1 = document.InsertParagraph();
				p1.Append("This is new section");
				document.Save();
			}
		}
	}

Please help.


Update Word Footer

$
0
0

I have a requirement to add and update the footer of .doc and .docx files whenever a document is added or updated in a SharePoint library. I am familiar with handeling the SharePoint side of this requirement. This is what I have come up with and this adds the SharePoint version number to the footer -

 
using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);
                try
                {
                    using (WordprocessingDocument document = WordprocessingDocument.Open(mem, true))
                    {
                        // Get the main document part
                        MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                        foreach (FooterPart footerPart2 in mainDocumentPart.FooterParts)
                        {
                            Footer footer = footerPart2.Footer;

                            Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };

                            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };

                            paragraphProperties1.Append(paragraphStyleId1);

                            Run run1 = new Run();
                            Text text1 = new Text();
                            text1.Text = "Document Version: " + fileversion;

                            run1.Append(text1);

                            paragraph1.Append(paragraphProperties1);
                            paragraph1.Append(run1);
                            footer.Append(paragraph1);
                        }
                    }
                }
                catch (System.IO.FileFormatException)
                {
                    //return ModifyDocumentResults.InvalidFileFormat;
                }
            }
I will have to update the version number every time the document is updated in SharePoint. How do I check if the version number part of the footer is already added to the documents footer? If it is added, how do I fetch the string that I added (text1)?

Page numbering in a word processing document

$
0
0

Hi,

I need help how to include page numbering in a wordprocessing document.

The document is generated on a web server (ASP.NET) (VB)

I need help with creating the extendedfile properties part, as well as referencing to .pages later on.

I´ve read a few answers, but they don´t work.

Thanks.

Update Document Footer

$
0
0

I have a requirement to add and update the footer of .doc and .docx files whenever a document is added or updated in a SharePoint library. I am familiar with handeling the SharePoint side of this requirement. This is what I have come up with and this adds the SharePoint version number to the footer -

 
using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);
                try
                {
                    using (WordprocessingDocument document = WordprocessingDocument.Open(mem, true))
                    {
                        // Get the main document part
                        MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                        foreach (FooterPart footerPart2 in mainDocumentPart.FooterParts)
                        {
                            Footer footer = footerPart2.Footer;

                            Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };

                            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };

                            paragraphProperties1.Append(paragraphStyleId1);

                            Run run1 = new Run();
                            Text text1 = new Text();
                            text1.Text = "Document Version: " + fileversion;

                            run1.Append(text1);

                            paragraph1.Append(paragraphProperties1);
                            paragraph1.Append(run1);
                            footer.Append(paragraph1);
                        }
                    }
                }
                catch (System.IO.FileFormatException)
                {
                    //return ModifyDocumentResults.InvalidFileFormat;
                }
            }
I will have to update the version number every time the document is updated in SharePoint. How do I check if the version number part of the footer is already added to the documents footer? If it is added, how do I fetch the string that I added (text1)?

How to get Word vba equivalent Selection.Range.XML using OpenXML sdk

$
0
0

Hi,

Is there any way to get the word's Range.xml using Open xml.

Regards,

Antony


Antony

OpenXML: Finding and Manipulating Embedded Charts in a Word Doc

$
0
0

I'm very close on this.

I'm trying to create a function that will locate and update an embeded chart within a Word document.  Ultimately, the document will have sevral charts.

So far, my function can iterate through the document and find a chart (currently there is only one) and plug in some dummy info.  It works, however when the document is opened, I get a pop-up complaining that the document is corrupt.  I OK past that and a second pop-up asks me if I'd like to recover the document.  I OK that and the document then opens and the chart is updated, all as if nothing were wrong.

So it winds up OK, but my users are not going to be happy with the "corrupt file" messages.  When they're not happy, no one is happy.

Also, I'm looking for a methodology to find and update a specific chart.  Currently I iterate through the document, and if I had to I could live with that but I'd like to implement something a little less fragile.

I was looking at perhaps using the "Title" property on the chart and attempting to have the SDK search for that.  I'm a relative newbie to this SDK and can't seem to locate an example of that (or *ANYTHING* for that matter that attempts to find a specific chart in a document).

Here is my code so far.  It's just a prototype, so it is maufacturing data for the cells and allthough it is iterating through the document, there is no method yet to target a specific chart:

	private void updateChart( WordprocessingDocument doc )
	{
		string rid = null;

		Stream stream = null;


		foreach ( Paragraph p in doc.MainDocumentPart.Document.Body.Elements<Paragraph>( ) )
		{
			foreach ( Drawing d in p.Descendants<Drawing>( ) )
			{
				foreach ( ChartReference cr in d.Descendants<ChartReference>( ) )
				{
					rid = cr.Id.Value;

					ChartPart cp = ( ChartPart )doc.MainDocumentPart.Parts.Where( pt => pt.RelationshipId == rid ).FirstOrDefault( ).OpenXmlPart;

					foreach ( ExternalData ed in cp.ChartSpace.Elements< ExternalData >( ) )
					{
						string externalDataRID = ed.Id.Value;
						EmbeddedPackagePart epp = ( EmbeddedPackagePart )cp.Parts.Where( pt => pt.RelationshipId == ed.Id ).FirstOrDefault( ).OpenXmlPart;

						using ( Stream str = epp.GetStream( ) )
						{
							using ( MemoryStream ms = new MemoryStream( ) )
							{
								CopyStream( str, ms );
								using ( SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open( ms, true ) )
								{
									ss.Sheet ws = ( ss.Sheet )spreadsheetDoc.WorkbookPart.Workbook.Sheets.FirstOrDefault( );

									string sheetId = ws.Id;

									WorksheetPart wsp = ( WorksheetPart )spreadsheetDoc.WorkbookPart.Parts.Where( pt => pt.RelationshipId == sheetId ).FirstOrDefault( ).OpenXmlPart;
									ss.SheetData sd = wsp.Worksheet.Elements<ss.SheetData>( ).FirstOrDefault( );

									int ctr = 0;
									foreach ( ss.Row row in sd.Elements< ss.Row >( ) )
									{
										if ( ctr > 0 && ctr <= 6 )
										{
											ss.CellValue cv0 = row.Elements<ss.Cell>( ).ElementAt( 0 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv0.Text = _monthsInRange[ ctr - 1 ].startDate.ToString( "MMM-yyyy" );

											ss.CellValue cv1 = row.Elements<ss.Cell>( ).ElementAt( 1 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv1.Text = ( ctr * 10 ).ToString( );

											ss.CellValue cv2 = row.Elements<ss.Cell>( ).ElementAt( 2 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv2.Text = ( ctr * 10 ).ToString( );

											ss.CellValue cv3 = row.Elements<ss.Cell>( ).ElementAt( 3 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv3.Text = ( ctr * 10 ).ToString( );

											ss.CellValue cv4 = row.Elements<ss.Cell>( ).ElementAt( 4 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv4.Text = ( ctr * 10 ).ToString( );

											ss.CellValue cv5 = row.Elements<ss.Cell>( ).ElementAt( 5 ).Elements<ss.CellValue>( ).FirstOrDefault( );
											cv5.Text = ( ctr * 10 ).ToString( );
										}++ctr;
									}
								}

								using ( Stream s = epp.GetStream( ) )
								{
									ms.WriteTo( s );
								}
							}
						}



						Chart chart = cp.ChartSpace.Elements<Chart>( ).First( );
						Bar3DChart bc = chart.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Bar3DChart>( ).FirstOrDefault( );

						if ( bc != null )
						{
							foreach( BarChartSeries bcs in bc.Elements<BarChartSeries>( ) )
							{
								CategoryAxisData cad = bcs.Descendants<CategoryAxisData>( ).FirstOrDefault( );

								StringReference sr = cad.Descendants<StringReference>( ).FirstOrDefault( );
								StringCache sc = sr.Descendants<StringCache>( ).First( );
								int ctr = 0;
								foreach ( StringPoint sp in sc.Descendants<StringPoint>( ) )
								{
									NumericValue nv = sp.Descendants<NumericValue>( ).First( );
									nv.Text = _monthsInRange[ ctr ].startDate.ToString( "MMM-yyyy" );++ctr;
								}


								foreach ( Values values in bcs.Descendants<Values>( ) )
								{
									NumberingCache nc = values.Descendants<NumberingCache>( ).First( );

									NumericValue nv1 = nc.Elements<NumericPoint>( ).ElementAt( 0 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv1.Text = "10";

									NumericValue nv2 = nc.Elements<NumericPoint>( ).ElementAt( 1 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv2.Text = "20";

									NumericValue nv3 = nc.Elements<NumericPoint>( ).ElementAt( 2 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv3.Text = "30";

									NumericValue nv4 = nc.Elements<NumericPoint>( ).ElementAt( 3 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv4.Text = "40";

									NumericValue nv5 = nc.Elements<NumericPoint>( ).ElementAt( 4 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv5.Text = "50";

									NumericValue nv6 = nc.Elements<NumericPoint>( ).ElementAt( 5 ).Elements<NumericValue>( ).FirstOrDefault( );
									nv6.Text = "60";
								}
							}
						}
					}
				}
			}
		}
	}

The embedded chart is based off a 5 column (well actually 6 - the first column is row headers) x 6 row spreadsheet.

Any help would be much appreciated.

JP


JP





How to Modify Embedded Chart Range

$
0
0

I am attempting to update a word template with embedded charts. I was successful in leveraging the code found here:

http://social.msdn.microsoft.com/Forums/office/en-US/8f7c6dbe-09b1-413c-8330-f0ea58b73eb4/openxml-finding-and-manipulating-embedded-charts-in-a-word-doc?forum=oxmlsdk#458a961e-57a6-4d3a-9468-9b0c99ba9fb0

I have not found a way, at this time, to modify the range of the existing chart. I may have some data sets which are larger than the template. the script correctly places the data within the Word Doc at the specified chart (using chart index, would be great if there were another way). How can i modify the range the chart uses?

Thanks,

Jeff

How to set relationship Id's properly when adding an ImagePart

$
0
0

Hi,

I am working with OOXML SDK 2.5 and a Word .docx document.

My objective is to create a method that will create a Paragraph containing an image from a byte array.

When I add the paragraph to a the document body, I want to see the image in the document.

The code below works for adding one image to a document, but as soon as I add multiple images,

all the image links appear broken in the Word document.

When I look at the generated document with the Productivity Tool, the relationship id is always 'rId4', 

regardless of the parameters to the AddImagePart method.


Can anybody assist please?  (Have burnt over 10 hours trying to debug this, and was just about to hit

Microsoft paid support, but the site is down at the moment.)






public static Paragraph CreateImageParagraph(WordprocessingDocument wordprocessingDocument, byte[] pngBytes) { var dimesionsInEmus = GetImageEmus(new MemoryStream(pngBytes), GetPageWidthInEmus(wordprocessingDocument)); MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png); imagePart.FeedData(new MemoryStream(pngBytes)); var relationshipId = mainPart.GetIdOfPart(imagePart); // for image properties: var guid = Guid.NewGuid().ToString(); string uniqueImageUri = String.Format("{{{0}}}", guid); var element = new Drawing( new DW.Inline( new DW.Extent() { Cx = dimesionsInEmus.Width, Cy = dimesionsInEmus.Height }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = guid }, 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 = guid + ".png" }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri = uniqueImageUri }) ) { 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 = dimesionsInEmus.Width, Cy = dimesionsInEmus.Height }), 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 }); return new Paragraph(new Run(element)); }



Problem of OLE Automation of Powerpoint 2010 with C++

$
0
0

Hi,

I'm playing with OLE automation of Powerpoint 2010 recently. I have written a piece of code as shown below. When the line "Shapes.AddPicture..." is executed, I always get an error. Who can tell be where am I wrong.

By the way, if Powerpoint 2003 is used, the code runs well. Thanks~

MSPPTApp = new CApplication0();
MSPPTApp.CreateDispatch(L"Powerpoint.Application");
CPresentations0 Presentations = MSPPTApp.get_Presentations();
CPresentation0 Presentation = Presentations.Add(FALSE);
CSlides0 Slides = Presentation .get_Slides();
CSlide0 Slide = Slides.Add((long)1, (long)1);
CShapes0 Shapes = Slide.get_Shapes();
Shapes.AddPicture(L"E:/image1.jpg", msoTrue, msoTrue, 0.0f, 0.0f, 100.0f, 100.0f);
Presentation.SaveAs(L"E:/1.pptx", ppSaveAsOpenXMLPresentation, 0);



How to get updated word contents from the Word Document using Open XML Sdk.

$
0
0

Hi Everyone,

I have created a Word Application in VSTO (C#). I have a Active word document where i have created lots of modifications like i have created some bookmarks, highlighted some text. Now after that i am creating wordprocessingdocument object by using fileStream of the same active document. Here is the code:

Stream stream = new FileStream(wdDocument.Path + "//" + wdDocument.Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordprocessingDocument wpd = WordprocessingDocument.Open(stream, false);

Now here the problem is, because the document is not saved i am not getting the updated contents from the WordProcessingDocument object. Is there any way to get the updated contents from the document without saving?

or is there any other way to load the active document to stream and read the contents from there?

Thanks,


Shahab Abbasi

Insert a Textbox into Excel using c#

$
0
0

hello

I need to add a textbox into a spreadsheet using OpenXML sdk and set it's content.  I don't mean adding text to a cell I mean as though you go into excel, go to the insert tab and select the Textbox option and draw a textbox at any location and any size.

I haven't found any information on the web about this at all so any help would be appreciated

Thanks

Making the Transition to Open XML

$
0
0

First and foremost, I’m really after information rather than specific answers. As I think everybody has heard the expression give a person a fish, they eat for a day. Teach them how to fish, they eat for a lifetime, so for me it’s Information that I’m after in this case, rather than a specific solution.

Fairly comfortable with VBA, and dipped my toe successfully into Microsoft.Office.Interop, but now my current project requires me to move with the time…, have made some progress. But I think its time to try and understand the model better before attempting any further progress. 

Ideally, I’m trying to track down a guide, book or web resource (yes I know how to use Google, but the www is big, very big and have read all the items of interest on the Forum) that gives reference from the older model, to the new one.

i.e

(please don’t flame me if I’m wrong)

VBA                                                                      OpenXML (SDK)

doc.storyRanges                                                  paragraghs

Ranges                                                                ?

Fields                                                                   ?

What I have found useful is actually making a copy and renaming to a Zipfile and going in and having a look at the xml to discover the element the information contains, Has anybody seen anything that matches up the directory structure with the MS Open XML SDK?

Thanks in Advance

LeTubs

Issue with removing charts from the spreadsheet using Open XML SDK v2

$
0
0

Hi,

I’m facing problem while removing the charts from the spreadsheet using OPN XML SDK v2.

Actual problem is not while saving the file after removing the chart part. But when I open the saved excel file it is telling me the file is not valid and is asking for recovering the file.

The problem seems to be with the drawing and the legacy drawing elements in the file. When I looked into the difference between the saved file and the file which was corrected by excel, the elements(Drawing, Legacy Drawing) have been removed.

I’m using below code for removing the charts from spreadhseet:

 using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true))
{
            WorkbookPart wbPart = document.WorkbookPart;
            var sheets = wbPart.GetPartsOfType<WorksheetPart>();

            foreach (var sheet in sheets)
            {
                sheet.DeletePart(sheet.DrawingsPart);
                sheet.DeleteParts<VmlDrawingPart>(sheet.VmlDrawingParts);

                //var drawingsParts = sheet.GetPartsOfType<DrawingsPart>();
                //if (drawingsParts != null)
                //{
                //    foreach (var dwgPart in drawingsParts)
                //    {
                //        dwgPart.DeleteParts<ChartPart>(dwgPart.ChartParts);

                //        //foreach (var chtPart in dwgPart.ChartParts)
                //        //{
                //        //    if (chtPart.ChartSpace != null)
                //        //    {
                //        //        chtPart.ChartSpace.RemoveAllChildren<Chart>();
                //        //        //Chart cht = chtPart.ChartSpace.GetFirstChild<Chart>();
                //        //        //cht.Remove();
                //        //    }
                //        //}
                //    }

                //    sheet.DeleteParts<DrawingsPart>(drawingsParts);
                //}


                //var vmlDrawingsParts = sheet.GetPartsOfType<VmlDrawingPart>();
                //if (vmlDrawingsParts != null)
                //{
                //    sheet.DeleteParts<VmlDrawingPart>(vmlDrawingsParts);
                //}

            }
}

Any help in this regard is highly appreciated.

Thanks,
Vinay TC

Viewing all 1288 articles
Browse latest View live


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