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

Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

$
0
0
Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

In one of our project we want to programmatically do mail-merge. That mean, we have an existing word document with mail-merge fields in it and when we run our code, values from table will be replaced in mail-merge fields of word document and the document will be saved with a new name.

The project is developed using asp.net, C# and open-xml.

Our code works, but not giving guaranteed results. That is, in one word document some fields get merged but few other do not. Please refer to attached code extract, we are using. The issue is for some of the nodes in nodelist (xnodeList), child nodes, data nodes getting generated as null. So getting Null reference exception.

Please suggest how to resolve this issue by suggesting a correction in code or any other method altogether. Please note we cannot use interops etc. (Microsoft.Office.Interop.Word) because this is a web application and we cannot install MS-Office on application server.


////////////////////////// CODE ////////////////////////////////////////

    using System.IO;
    using System.Xml;
    using DocumentFormat.OpenXml.Packaging;
    using System.IO.Packaging;
    using System.Xml.Linq;
    using WordDocument = DocumentFormat.OpenXml.Wordprocessing;
    protected void mail_merge_file1()
        {
    
      FileInfo fi;
     Object oTemplatePath = AppConstants.TemplatesUpload + hdnTemplatePath.Value.ToString().Trim();
    
    fi = new FileInfo(oTemplatePath.ToString());
    oFileName = lstActualFilePath[0].FilePath + fi.Name.ToString().Replace(fi.Extension, "MM") + fi.Extension;
    // if file exists
    if (System.IO.File.Exists(oTemplatePath.ToString()))
                    {
    
                        XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
    
                        nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                        PackagePart packagePart;
                        XmlNodeList nodes;
                        XmlNodeList nodes1;
                        XmlNode parentnodes;
                        XmlNode childnode;
                        XmlNode Datanode;
                        string columnname;
                        int N = 1;
                        int br = 1;
                        string strDateTimeFormat = string.Empty;
                        string strDateTimeString;
                        int intIndexofDatestart;
                        string strrootnode;
                        XmlNode root;
    
                        File.Copy(oTemplatePath.ToString(), oFileName.ToString(), true);
                        
                        // open file , read the contents of file into an byte array
                        byte[] sourceBytestemp = File.ReadAllBytes(oFileName.ToString());
                        using (MemoryStream _workingMemoryStream = new MemoryStream())
                        {
                            // Load block of bytes into memory
                            _workingMemoryStream.Write(sourceBytestemp, 0, sourceBytestemp.Length);
                            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(_workingMemoryStream, true))
                            {
                                XElement newBody = XElement.Parse(wordDocument.MainDocumentPart.Document.Body.OuterXml);
                                // Delete MailMerge Data Source Part
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    //populate all nodes of mergefields from the file
                                    IList<XElement> xnodeList = (from el in newBody.Descendants()
                                        //select el).ToList();
                                        where el.Name.LocalName == "t" && el.Value.StartsWith("«")
                                        select el).ToList();
                                    // fetch each node 1 by 1,remove child nodes and replace data nodes's value with the value of the record.    
                                    foreach (XElement xnode in xnodeList)
                                    {
                                        columnname = xnode.Value.ToString().Substring(1, xnode.Value.ToString().Length - 2);
                                        if (ds.Tables[0].Columns.Contains(columnname))
                                        {
                                            
                                            XElement xchildnode = (XElement)xnode.Parent.NextNode;
                                            //below line is getting exception as xchildnode is getting generated "null" value in case of some nodes/columns (xnode).
                                            xchildnode.Remove();
                                            
                                            XElement xDatanode = (XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode;
                                            if (((XElement)xDatanode).Value.ToString().Contains("\\"))
                                            {
                                                if (ds.Tables[0].Columns[columnname] != null)
                                                {
                                                    intIndexofDatestart = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().IndexOf("\\");
    
                                                    strDateTimeString = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().Trim();
                                                    switch (xDatanode.Value.ToString().Substring(intIndexofDatestart, 2))
                                                    {
                                                        case "\\@":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 3, strDateTimeString.Length - (intIndexofDatestart + 4));
                                                            break;
                                                        case "\\#":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 2, strDateTimeString.Length - (intIndexofDatestart + 2));
                                                            break;
                                                    }
                                                    if (ds.Tables[0].Columns[columnname].DataType == Type.GetType("System.DateTime"))
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            ((XElement)xnode).Value  = Convert.ToDateTime(ds.Tables[0].Rows[i][columnname].ToString()).
                ToString(strDateTimeFormat);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            /*new code*/
                                                            ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                            /*new code ends*/
                                                        }
    
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                {
                                                    ((XElement)xnode).Value = "";
                                                }
                                                else
                                                {
                                                    ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                }
                                            }
    
                                            for (int k = 0; k < 3; k++)
                                            {
                                                xchildnode = (XElement)xnode.Parent.PreviousNode;
                                                xchildnode.Remove();
                                            }
    
                                        }
    
                                        ///adding page break .
                                        ///
                                        if (i + 1 < ds.Tables[0].Rows.Count)
                                        {
    
                                            IList<XElement> xnodes = (from el in newBody.Descendants()
                                                                      //select el).ToList();
                                                                      where el.Name.LocalName == "sectPr"
                                                                      select el).ToList();
                                            /// end Adding document for next row
                                        }
                                        else
                                        {
                                            wordDocument.MainDocumentPart.Document.Body = new WordDocument.Body(newBody.ToString());
                                            wordDocument.MainDocumentPart.Document.Save();
                                        }
    
                                    }
                                }
                                DocumentSettingsPart settingsPart = wordDocument.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
                                // Delete reference to Mail Merge Data sources
                                XElement settings = XElement.Parse(settingsPart.RootElement.OuterXml);
                                IList<XElement> mailMergeElements =
                                    (from el in settings.Descendants()
                                     where el.Name.LocalName == ("mailMerge")
                                     select el).ToList();
    
                                foreach (XElement field in mailMergeElements)
                                {
                                    field.Remove();
                                }
                                settingsPart.RootElement.InnerXml = settings.ToString();
                                settingsPart.RootElement.Save();
    
                                // Save in output directory
                                // Create a new document based on updated template
                                using (FileStream fileStream = new FileStream(oFileName.ToString(), FileMode.Create))
                                {
                                    _workingMemoryStream.WriteTo(fileStream);
                                }
                            }
                        }
                    }
    
    
        }   

           

How to Wrap the Japanese Text in the WordML?

$
0
0

Hi,

I am having a requirement  where I need to display the Japanese Text in WordML. I am able to display the Japanese text using the wordml and opening the document in microsoft word 2013  but the text is not wrapping to next lines as the Japanese text is long in length .

Can anyone suggest the solution for wrapping the Japanese text in WordML.

Thanks in Advance!!!

Thanks.


Disable Macros in OpenXml using asp.net

$
0
0

Hi I am using OpenXml in asp.net . In that i am trying to open the macro enabled excel and insert the data into the excel. For that i needs to disable all the macros in the Excel. Then only i can able to write into that. Is there anyway to disable it ? . 

Please help me out. 

Unable to add an image to an Excel Spreadsheet using OpenXML SDK 2.5

$
0
0

I have been tasked with what I thought would be a relatively simple job of processing an Excel Spreadsheet, reading some values from a row, drawing an imaged based on that information and then place that image in a cell.

I downloaded Open XML SDK 2.5, used Google and started. It's a lot more complicated than I thought, and by complicated I mean a lot more lines of code, but I found some examples and wrote the code. Parsing the information from the cells in the row was simple, as was drawing the image, but adding the image back to the worksheet so far has failed. In fact, in my initial trial, the resulting file, after adding 10 images is considerably smaller than the original and on top of that it refuses to open with a message that essential parts are missing.

So instead of working with live data, I created an extremely simple spreadsheet. This has "A" in A1, 24 in B1 and 36 in B2. I parse this information, and draw a line from the top left to bottom right of a rectangle 24 by 36. Then I add the image back to the worksheet. Examination of the resulting file shows that the image is there, but opening the spreadsheet in Excel doesn't show the image.

I used this as an example of code that is supposed to do this. I modified the code, mainly to make the function an extension Method on Worksheet. Other than that, the code is intended to be identical. But it doesn't work. 

Below are all the various pieces of code. First the Main program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Pictures;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using System.Drawing;
using OpenXMLExtensions;
using System.IO;

namespace ExcelApp
{
    delegate string GetCell(int i);
    class Program
    {
        enum columns { Mark, W, H };
        static void Main(string[] args)
        {
            using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(@"C:\Users\user\Documents\practise.xlsx", true))
            {

                SharedStringTablePart sstp = mySpreadsheet.WorkbookPart.SharedStringTablePart;
                SharedStringTable sst = sstp.SharedStringTable;

                WorkbookPart wb = mySpreadsheet.WorkbookPart;
                IEnumerable<Sheet> sheets = mySpreadsheet.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Sheet1");
                if (sheets.Count() == 0) return;

                WorksheetPart worksheetPart = (WorksheetPart)mySpreadsheet.WorkbookPart.GetPartById(sheets.First().Id);

                Worksheet worksheet = worksheetPart.Worksheet;
                int startRow = 1;
                int lastRow = 1;

                foreach (Row row in worksheet.Descendants<Row>().Where(r => r.RowIndex.Value >= startRow && r.RowIndex.Value <= lastRow))
                {
                    uint rowIndex = row.RowIndex.Value;
                    Cell[] cells = row.Descendants<Cell>().ToArray();
                    GetCell gc = delegate(int i)
                    {
                        return (cells[i].CellValue == null) ? "0" : cells[i].CellValue.Text;
                    };
                    Artifact artifact = new Artifact();
                    artifact.Mark = sst.ElementAt(int.Parse(gc((int)columns.Mark))).InnerText;
                    artifact.H = double.Parse(gc((int)columns.H));
                    artifact.W = double.Parse(gc((int)columns.W));
                    Bitmap bmp = artifact.Draw();
                    worksheet.InsertImage(rowIndex * 100, rowIndex * 100, 100, 200, bmp, ImagePartType.Bmp);
                }
                worksheet.Save();
            }
        }
    }

}

And now the object that is drawn:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace ExcelApp
{
    class Artifact
    {
        private const int ppi = 8; // Since the dimensions are in inches ppi is the "Pixels per inch" for the drawing
        public string Mark { get; set; }
        public int Quantity { get; set; }
        public double W { get; set; }
        public double H { get; set; }

        public Artifact() { }
        public Bitmap Draw()
        {
            Bitmap bmp = new Bitmap((int)W * ppi, (int)H * ppi);
            using (Graphics go = Graphics.FromImage(bmp))
            {
                Pen pen = new Pen(Color.Red);
                go.DrawLine(pen, new Point(0, 0), new Point(bmp.Width - 1, bmp.Height - 1));
                                return bmp;
            }
        }
    }
}

And now the Extension Method based on the link shyown above:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Pictures;
using S = DocumentFormat.OpenXml.Drawing.Spreadsheet;
using System.IO;
using System.Drawing;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using System.Drawing.Imaging;

namespace OpenXMLExtensions
{
    public static class OpenXMLExtensions
    {
        public static void InsertImage(this Worksheet ws, long x, long y, long? width, long? height, Bitmap bm, ImagePartType ipt)
        {
            try
            {
                WorksheetPart wsp = ws.WorksheetPart;
                DrawingsPart dp;
                ImagePart imgp;
                WorksheetDrawing wsd;

                if (wsp.DrawingsPart == null)
                {
                    //----- no drawing part exists, add a new one
                    dp = wsp.AddNewPart<DrawingsPart>();
                    imgp = dp.AddImagePart(ipt, wsp.GetIdOfPart(dp));
                    wsd = new WorksheetDrawing();
                }
                else
                {
                    //----- use existing drawing part
                    dp = wsp.DrawingsPart;
                    imgp = dp.AddImagePart(ipt);
                    dp.CreateRelationshipToPart(imgp);
                    wsd = dp.WorksheetDrawing;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    bm.Save(ms, ImageFormat.Bmp);
                    ms.Seek(0, SeekOrigin.Begin);
                    imgp.FeedData(ms);
                }

                int imageNumber = dp.ImageParts.Count<ImagePart>();
                if (imageNumber == 1)
                {
                    Drawing drawing = new Drawing();
                    drawing.Id = dp.GetIdOfPart(imgp);
                    ws.Append(drawing);
                }

                S.NonVisualDrawingProperties nvdp = new S.NonVisualDrawingProperties();
                nvdp.Id = new UInt32Value((uint)(1024 + imageNumber));
                nvdp.Name = "Picture " + imageNumber.ToString();
                nvdp.Description = "";
                DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                picLocks.NoChangeAspect = true;
                picLocks.NoChangeArrowheads = true;
                S.NonVisualPictureDrawingProperties nvpdp = new S.NonVisualPictureDrawingProperties();
                nvpdp.PictureLocks = picLocks;
                S.NonVisualPictureProperties nvpp = new S.NonVisualPictureProperties();
                nvpp.NonVisualDrawingProperties = nvdp;
                nvpp.NonVisualPictureDrawingProperties = nvpdp;

                DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

                S.BlipFill blipFill = new S.BlipFill();
                DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                blip.Embed = dp.GetIdOfPart(imgp);
                blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
                blipFill.Blip = blip;
                blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                blipFill.Append(stretch);

                DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
                DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
                offset.X = 0;
                offset.Y = 0;
                t2d.Offset = offset;
                //Bitmap bm = new Bitmap(image);

                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();

                if (width == null)
                    extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                else
                    extents.Cx = width;

                if (height == null)
                    extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                else
                    extents.Cy = height;

                bm.Dispose();
                t2d.Extents = extents;
                S.ShapeProperties sp = new S.ShapeProperties();
                sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                sp.Transform2D = t2d;
                DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                sp.Append(prstGeom);
                sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                picture.NonVisualPictureProperties = nvpp;
                picture.BlipFill = blipFill;
                picture.ShapeProperties = sp;

                S.Position pos = new S.Position();
                pos.X = x;
                pos.Y = y;
                Extent ext = new Extent();
                ext.Cx = extents.Cx;
                ext.Cy = extents.Cy;
                AbsoluteAnchor anchor = new AbsoluteAnchor();
                anchor.Position = pos;
                anchor.Extent = ext;
                anchor.Append(picture);
                anchor.Append(new ClientData());
                wsd.Append(anchor);
                wsd.Save(dp);
            }
            catch (Exception ex)
            {
                throw ex; // or do something more interesting if you want
            }
        }
    }
}

If anyone can spot what I am doing wrong I would be grateful for the help.

It also occurs to me that it would be a good idea to develop a lot of Extension Methods to augment the SDK because that extension method I wrote is a vast amount of code to write just to add a picture into a cell. If anyone has started such a project I'd be interested in hearing from them.

Excel Pagination Issue

$
0
0

Hi,

I am using office open sdk to create Excel files. But when we are opening the same excel in Windows and Mac operating systems, its showing different number of columns on each page while we set layout as page layout. All page setup settings are same.

For reference, I am attaching screen shot of generated excel sheet. In first Screen Shot, which refers to windows is showing 10 columns. In second screen shot, which refers to Mac is showing 9 columns.

Please help me out.

Thanks,

Naveen Khanna

How to get value from active-x Textbox control in Word

$
0
0

Create active-x Textbox control in Word. Enter some text in it like "box1box". Then using OpenXml Tool to open file and reflect code. You will not able to see the text string since they are images. Something like these:

   <w:object w:dxaOrig="1440" w:dyaOrig="1440">
      <v:shapetype id="_x0000_t75" coordsize="21600,21600" filled="f" stroked="f" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
        <v:stroke joinstyle="miter" />
        <v:formulas>
          <v:f eqn="if lineDrawn pixelLineWidth 0" />
          <v:f eqn="sum @0 1 0" />
          <v:f eqn="sum 0 0 @1" />
          <v:f eqn="prod @2 1 2" />
          <v:f eqn="prod @3 21600 pixelWidth" />
          <v:f eqn="prod @3 21600 pixelHeight" />
          <v:f eqn="sum @0 0 1" />
          <v:f eqn="prod @6 1 2" />
          <v:f eqn="prod @7 21600 pixelWidth" />
          <v:f eqn="sum @8 21600 0" />
          <v:f eqn="prod @7 21600 pixelHeight" />
          <v:f eqn="sum @10 21600 0" />
        </v:formulas>
        <v:path gradientshapeok="t" o:connecttype="rect" o:extrusionok="f" />
        <o:lock v:ext="edit" aspectratio="t" />
      </v:shapetype>
      <v:shape id="_x0000_i1031" style="width:220.65pt;height:18pt" alt="altbox1" o:ole="" type="#_x0000_t75" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
        <v:imagedata o:title="" r:id="rId5" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
      </v:shape>
      <w:control w:name="TextBox1" w:shapeid="_x0000_i1031" r:id="rId6" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
    </w:object>

Controlling display width when applying a stylesheet to an xml file

$
0
0

I'm writing my first XSLT for a rather complicated XML.  

My problem is this.  What I'd like to do is limit the width of the display to the width of the browser window.  

The XSLT is still rather simple, the entire thing enclosed in a table.  I've tried setting the table width to 100% (no other width settings in the entire table) but still the displayed data is too wide for the screen and has a horizontal scroll bar.

How do I deal with this?

How to remove empty value mail merge fields?

$
0
0

Hi,

I am trying to generate mail merge document using open xml. I can generate the document but if there was no value found for a merge field, it leaves an empty space. If there is no value found for a mail merge field I would like to remove/delete it so the finally generated document does not have any blank spaces.

Regards


Freeze panes

$
0
0

I am trying to freeze panes using this code, but sheetViews always comes up null.  I have tried to add SheetViews, but apparently I don't know what I am doing.  Can you help?

        private static void FreezeTopRow(SpreadsheetDocument spreadsheetDocument)
        {
            WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
            SheetViews sheetViews = worksheetPart.Worksheet.GetFirstChild<SheetViews>();
            SheetView sheetView = sheetViews.GetFirstChild<SheetView>();
            Selection selection = sheetView.GetFirstChild<Selection>();
            Pane pane = new Pane() { VerticalSplit = 1D, TopLeftCell = "A2", ActivePane = PaneValues.BottomLeft, State = PaneStateValues.Frozen };
            sheetView.InsertBefore(pane, selection);
            selection.Pane = PaneValues.BottomLeft;
        }


Kipp Woodard

SmartArt Algorithm

$
0
0

Is there someone could help me ,some problem with SmartArt in office 2007. i konw SmartArt have  snake Algorithm,linear Algorithm and so on,but i can't get the right position of shape's and the right width of shape's,is there some information forget,or some information in Algorithm i can't get?

i would be happy to any answer.Thanks!

How to execute/call macro in .xlsm file using Office Open XML SDK 2.0

$
0
0

I would like to know how OpenXML API can be used to run macros with .xlsm files? I'm using Open XML API in my project and using "using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(excelPath, true))" to open the excel file and then inserting the values in excel file using Open XML API's, through a windows service.

ISSUE -  After inserting the values, we are uploading the .xlsm file to a SharePoint library. When user/client opens the file, .xlsm file opens and We are running a macro (implementing formulas) on open event of the excel. However, when user open in Office 2010, they don't see their data populated through macro but when they open in Office Excel 2013, the macro runs properly, and data is also populated.

Question - I think this is the issue related to "How we are calling MACRO". Can we call our macro through .NET C# Code in OPEN XML API instead of calling on open event of excel file itself..? Through this way, I think, we will also be able to present .xlsx file to our client (as client needs .xlsx file and not .xlsm).

Please suggest !!!


Vipul Jain

Error while open the excel sheet

$
0
0

Hi,

   I loaded the values in excel sheet by using open xml, but while open the excel sheet it show the error message like below, can you tell me how to address this errors? is any specific tool available to address this errors?

Error during open the excel sheet

$
0
0

When i open the excel sheet, i am getting following popup, so i compare two excel file(with errro popup, without error popup), so i got below(screen short2), but i could not able to find exact error and which field causing error, so can any one help me to solve this issue.

Screen Short1:

Screen Short2:

Protecting Excel file created through OpenXML

$
0
0

Hello,

I want to protect Excel file 2007+ version (xlsx), which is created through OpenXML 2.0. I am able to protect the file through zipped format. I am not able to find the help to protect the Excel file i.e., assigning password to open for Excel file. This is not the help for protecting the worksheet.

Can anybody help me out?

The hostname could not be parsed excetion at SpreadsheetDocument.Open(fileName, editable) in VS2013

$
0
0

Hi,

I have opened a VS2010 Console application in VS2013.(Migration happened automatically)

Now, I am trying to open an document using

SpreadsheetDocument.Open(fileName, editable)

and fileName is "C:\\TestAutomationEnvironment\\UIControlsDescription\\UIControlsDescription.xlsx"

and at this open we are getting

The hostname could not be parsed excetion.

and it was working fine with VS2010.

Whether it is producing the exception because of VS2013?


Exporting data and chart to excel using openxml asp.net mvc

$
0
0

Hi,

I am new to OpenXML,

I have two requirement that has to completed using ASP.NET MVC and OpenXML(or any option).

Requirement 1. Data and chart has to be exported to MS excel (on click of button user should be given option to save or open directly - just like downloding document from internet)

Requirement 2. In the exported excel, when the user changes the data, the chart also need to change based on value(just like creating chart in MS excel and changing its data)

Is this possible in OpenXML, If possible is there any refernce document. If not possible is there any other way to achive this. Interop excel libarary is ruled out since we cannot install excel in production server.

Please help me!

Thanks

soniya

Reading heavy excel files page wise using OpenXML

$
0
0

Hi, 

I am using OpenXML to read heavy excel files, but I am using paging to read files because I have to process data and show in Grid on frontend. 

Problem here is for reading every page of 10000 records its time is increasing. 

First Page = 38397 Milliseconds

Second Page = 81910 MS

Third page =117923 MS

Fourth page =150142 MS

Any body has any clue...

Open XML SDK v2 Handling Multiple Threads

$
0
0

Hi

I have read a post or two that suggests the open XML sdk is not thread safe but I haven't found any official MS document that states this in fact to the contrary most online docs demonstrate how to use the SDK for serverside creation of office documents. I'm prototyping a windows service that reads MSMQ and dispatches a thread to export some data to excel using open xml sdk v2.  The thread is created by calling BeginInvoke on a delegate and ultimately calls this code:

using

(SpreadsheetDocument workBook =SpreadsheetDocument.Open(exportFileInfo.FullName,true))

{

 

WorkbookHelper workBookHelper =newWorkbookHelper(workBook.WorkbookPart, tableName);

exportRowCount =

this.DataBind(workBookHelper, datasource);

workBook.WorkbookPart.Workbook.Save();

workBook.Close();

 

 

return exportRowCount;

}

If I allow 2 or more threads to run concurrently:

  • The code never finishes when I try to export 10000 rows. (I suspect I'm getting deadlock but not sure how to verify this). 
  • It does work if I try to export 5000 rows or less.

If I comment out the calls to save() and close() the code always finishes no matter how many threads I allow to run.  If I allow just one thread to run the exports always works.

Is there a threading problem in the SDK related to saving and closing workbooks and if so is there a plan to fix it soon?

Other than synchronising the entire block of code above is there a way I can I fix the problem myself?

Regards







 

Looking for examples using OpenXML SDK

$
0
0

I am looking for examples of using the OpenXML SDK such as

  • Opening a DOCX or xlsx or xlsm
  • Select specific sub xml files in a docx, xlsx, or xlsm
  • Search for and parse specific node  in the sub xml file
  • What is best tool for this? Something like xPath or other

Thank you,

Jim


Jim

how to write RTF to docx file

$
0
0

i have RTF store in string, how is the best way to insert it to docx via open xml.

the follwing go do the job but the document open with error.

 

using (WordprocessingDocument myDoc =
		  WordprocessingDocument.Open("RtfTest2.docx", true))
		{string val = @"{\rtf1 \b Hello world! \b0 }";

			MainDocumentPart mainPart = myDoc.MainDocumentPart;
			//Find content controls that have the name of the source file as // an alias value. 
			List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().Where(s =>"RichText".Contains(s.SdtProperties.GetFirstChild<Tag>().Val.Value)).ToList();if (sdtList.Count != 0)
			{string altChunkId = "AltChunkId" + Guid.NewGuid();
				AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);// convert string to stream  byte[] byteArray = Encoding.ASCII.GetBytes(val);using (var stream = new MemoryStream(byteArray))
				{
					chunk.FeedData(stream);
				}var altChunk = new AltChunk();
				altChunk.Id = altChunkId;//Replace the content control with altChunk information. foreach (SdtBlock sdt in sdtList)
				{
					OpenXmlElement parent = sdt.Parent;
					parent.InsertAfter(altChunk, sdt);
					sdt.Remove();
				}
				mainPart.Document.Save();
			}
		}


please help..


tt
Viewing all 1288 articles
Browse latest View live


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