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

Shapes with Open XML SDK

$
0
0

Hi Team Open XML.

I started working on OOXML from past 1 month and I encountered so many good things about the SDK and its written beautifully. I would like to take this opportunity to thanks to OOXML Team.

I have the following question for the day with respect to reading word documents using OOXML:

1. Shapes from Microsoft Word (2007, 2010 or 2013) are DrawingML Objects as per spec, However there exists a Multiple Group tags for those objects when I view the document in Open XML SDK 2.5. This makes me hard to read those docs and decide what to do with those objects. What are the reasons for more than one Group objects in the Open XML API? When there is only one DrawingML Object? Also it co-exists with these group elements in that Run Tag.

2. I am having hard time adding these VML objects and convert them to HTML to render into the UI. Therefore I want to know if there exists a way to get the exact location of these VML Objects in the word document? The moment I copy-paste these objects in the word document manually, the position of these objects are unknown. Later when I drag these shapes to some other location in the word document, SDK 2.5 does not read them at that position. What could be the reason?

Please let me know

Thanks,

Triguna



Create a new shape in the slide master

$
0
0

I am having trouble appending a shape to a slide master. I am trying to insert a textbox with some text in the slide master, like a footer. I am very new to openxml and I was wondering if someone can help me. When I use my code below, I end up corrupting my presentation file. Any help is very much appreciated:

PresentationPart

SlideMasterPart smPart = (SlideMasterPart)presentationPart.GetPartById("rId1");

CommonSlideData sldData = smPart.SlideMaster.CommonSlideData;

ShapeTree shapeTree = (ShapeTree)sldData.ShapeTree;

Shape shape =newShape();

NonVisualShapeProperties nonVisualShapeProperties = newNonVisualShapeProperties() ;

NonVisualDrawingProperties nonVisualDrawingProperties = newNonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "Footer" };

NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties = newNonVisualShapeDrawingProperties();

ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = newApplicationNonVisualDrawingProperties();

nonVisualShapeProperties.Append(nonVisualDrawingProperties);

nonVisualShapeProperties.Append(nonVisualShapeDrawingProperties);

nonVisualShapeProperties.Append(applicationNonVisualDrawingProperties);

 

TextBody textBody =newTextBody();Paragraph paragraph = new A.Paragraph();

A.

ParagraphProperties paragraphProperties = new A.ParagraphProperties() { DefaultTabSize = 1018167 };

A.

DefaultRunProperties defaultRunProperties = new A.DefaultRunProperties();

paragraphProperties.Append(defaultRunProperties);

A.

Run run =new A.Run();

A.

RunProperties runProperties = new A.RunProperties() { Language = "en-US", FontSize = 700, Dirty = false };

runProperties.SetAttribute(

newOpenXmlAttribute("","smtClean","","0"));Text text = new A.Text();

text.Text =

"© 2014 XYZ Limited-------------";

run.Append(runProperties);

run.Append(text);

paragraph.Append(paragraphProperties);

paragraph.Append(run);

textBody.Append(paragraph);

shape.Append(textBody);

shapeTree.Append(shape);

presentationPart.Presentation.Save();

A.

A.

presentationPart = pptDoc.PresentationPart;

Copy table from Excel to Word

$
0
0

Is it possible to copy content from Excel to Word using OpenXML 2.5?

Case: Excel file has Charts and regions of data. All of them are using defined names to identify.

Now I need to copy some of them into Word document which contains exactly same name as defined name in excel (could be part of text or merging field, not sure yet).The problem is, sometimes it should be copied as MetafileImage, sometimes EnhancedMetafileImage, sometimes Text, or html or rtf.

 

Right now I'm using Interop, which is really slow.

Generated docx, problem with editing in OWA/WAC

$
0
0

Hi!

I have successfully created a docx from a dotx with C#/OpenXML. I added an XML with some properties and the docx gets populated just fine with the custom values. I upload the document to SharePoint Online and can preview the document just fine. When i try to edit the document all the custom properties that have been populated are grayed out and can't be edited. I guess this is a limitation in OWA/WAC but i would like to get this confirmed and i have not been able to find any information regarding this. I've also tried to use "built in" properties like Title, Author and so on but the result is the same.

Thank you!

EDIT:

If there is any workaround for the "issue" i would appreciate any guidance. Is there any way to "print" the contents of the document to a new blank docx so that all the mappings/xml-stuff are removed? If thats possible that would absolutely be a good workaround.

Footer not updating on first page

$
0
0

Hi,

i am trying to perform merging on a template - for that

1. i had copied my word template, now append my first document file into it

2. now i had added one more word template in that file

3. i deleted the existing footer from the file and added my own footer into that.

 in the resultant file i am getting the footer of first template  and in the left whole document the new one which i had added.

 help me to resolve this. 

Create doughnut chart using openxml

$
0
0
I want to create doughnut chart using openxml, c# in power point. I have got code to create pie chart. Any one can help me out in creating doughnut chart

Is it possible to add two or more Worksheets in the same WorksheetPart?

$
0
0

I am a newbie in using OpenXML SDK and I'm trying to add two worksheets in a spreadsheet document. The first sheet is added just fine, but the code for adding second sheet is giving exception that I still couldn't figure out. Below is my code-

//Creating a Spreadsheet File SpreadsheetDocument doc = SpreadsheetDocument.Create("E:\\TestFile.xlsx", SpreadsheetDocumentType.Workbook); //Creating a Workbook part and adding a workbook to it WorkbookPart workbookpart = doc.AddWorkbookPart(); workbookpart.Workbook = new Workbook(); //Adding a new worksheet part and and a worksheet WorksheetPart worksheetPart; worksheetPart = doc.WorkbookPart.AddNewPart<WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData()); //Adding a Sheets tag in the Workbook Sheets sheets = doc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets()); //Initializing a worksheet Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = doc.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = (uint)(doc.WorkbookPart.Workbook.Sheets.Count() + 1), Name = "TestSheet" }; sheets.Append(sheet); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); Row row; row = new Row(){RowIndex = 1}; //Adding the row in the sheet data sheetData.Append(row); Cell refCell = null; foreach (Cell cell in row.Elements<Cell>()) { if (string.Compare(cell.CellReference.Value,"A1",true)>0) { refCell = cell; break; } } Cell newCell = new Cell(){CellReference = "A1"}; row.InsertBefore(newCell, refCell); newCell.CellValue = new CellValue("Test Value One"); newCell.DataType = new EnumValue<CellValues>(CellValues.String); doc.WorkbookPart.Workbook.Save(); //Adding a new Sheet WorksheetPart newworksheetpart = doc.WorkbookPart.AddNewPart<WorksheetPart>(); newworksheetpart.Worksheet = new Worksheet(); sheets = doc.WorkbookPart.Workbook.GetFirstChild<Sheets>(); Sheet newsheet = new Sheet() { Id = doc.WorkbookPart.GetIdOfPart(worksheetPart), Name = "SecondSheet", SheetId = 2 }; sheets.Append(newsheet); SheetData newsheetdata = newworksheetpart.Worksheet.AppendChild(new SheetData()); Row newrow = new Row(){RowIndex = 1}; newsheetdata.Append(newrow); Cell newrefcell = null; foreach (Cell cell in r.Elements<Cell>()) { if(string.Compare(cell.CellReference.Value,"A1",true)>0) { newrefcell = cell; break; } } Cell newcell = new Cell(){CellReference = "A1"}; newrow.InsertBefore(newcell, newrefcell); newcell.CellValue = new CellValue("Test Value Two"); newcell.DataType = new EnumValue<CellValues>(CellValues.String); doc.WorkbookPart.Workbook.Save(); doc.Close();

The exception is "Cannot insert the OpenXmlElement "newChild" because it is part of a tree." in the underlined line.

And I find the concept of WorksheetPart and Worksheets somewhat confusing. So far I haven't found any good source where adding multiple sheets is demonstrated, and my understanding from the official documentation is that we need a different worksheetpart for each worksheet- is that correct?

Copy header with image from a docx file to another using open xml and c#

$
0
0

Hello,

I'm a newbie but I'really would like to learn as much as possible about c# and the manipulation of docx files...

I'm writing a program to merge some docx file to create a new file and it works quite well :) but i'm not able to copy the header and the footer from a template...

I tried to use the code to replace the header that i found on msdn help but no header is created :(

The point is that my header is an image and I'm not able to copy it...

Does someone can help me? Maybe, if it's possible, can you show me a code that copy an header with images to another one?

Thanks,

Cristina


PowerPoint: How to change footer in slide on shape stores in master

$
0
0

Hi.

like to set the footer text on a slide. I can set it with the following code, but it appears not at the location defined in the master. I am quite new to OpenXML, perhaps somebody can give me a hint.

Actually using the following function to create shape with Placeholder like Title or Footer. But the shapes appears at the same location and not in the footer, SubTitle,... positions defined in the master.

 slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(GenerateTitleShape(Slide.Title, PlaceholderValues.Title));
                        slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(GenerateTitleShape(Slide.SubTitle, PlaceholderValues.SubTitle));
                        slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(GenerateTitleShape(Slide.Title, PlaceholderValues.Footer));

private Shape GenerateTitleShape(string title, PlaceholderValues type ) { _DrawingObjectId++; Shape titleShape = new Shape(); titleShape.NonVisualShapeProperties = new NonVisualShapeProperties (new NonVisualDrawingProperties() { Id = _DrawingObjectId, Name = "Title" }, new NonVisualShapeDrawingProperties(new a.ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = type })); titleShape.ShapeProperties = new ShapeProperties(); // Specify the text of the title shape. titleShape.TextBody = new TextBody(new a.BodyProperties(),new a.ListStyle()); titleShape.TextBody.Append(new a.Paragraph(new a.Run(new a.Text(title)))); return titleShape; }




Validator missing something

Spreadsheet created by OpenXml SDK 2.5 failing validation without any details

$
0
0

I am trying to create a spreadsheet using Open XML SDK 2.5, and although the file can be opened in MS Excel, it gives a prompt-

"We found a problem with some content in "filename.xlsx". Do you want us to recover as much as we can?"

If i click yes, it opens the excel just fine, with a message-

"Repaired Records: Cell information from /xl/worksheets/sheet.xml part".

I tried to validate the generated fine in Open XML SDK Productivity tool, where it gives following error description for almost all the cells-

"Element 'DocumentFormat.OpenXML.Spreadsheet.CellFormat' referenced by 'c@s' does not exist in part '/WorkbookPart/WorkbookStylesPart'. The index is '1'."

What am I missing? I have not added any style information or stylepart in the spreadsheet, yet this probably is related to style information. Is adding a stylepart mandatory?

Insert a new paragraph inside a merge field

$
0
0

Hi,

I dont know if somebody asked this before (i've searched about it).

I am trying to insert a new Paragraph inside a merge field using this code:

mergefield.AppendChild(new Paragraph(new Run(new Text("New paragraph"))));

And when I execute my program it works ok, but when I try to open the merged document there is an error related to document format.

So, what am I doing wrong ? Is there any other approach for that ? 

It only works when I do the following:

mergefield.AppendChild(new Run(new Text("New paragraph")));

How to create multiple worksheets in an Excel workbook and write to the worksheets individually?

$
0
0


I got error opening the Excel file after adding the second worksheet with the following code.  The error message was "We found a problem with some content in 'Test.xlsx.' Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes."  I clicked "Yes".  Next message was "The workbook cannot be opened or repaired by Microsoft Excel because it is corrupt."

var worksheetPart2 = workbookPart.AddNewPart<WorksheetPart>();
var relationshipId2 = workbookPart.GetIdOfPart(worksheetPart2);
var sheetSuspense = new Sheet { Name = "Suspense Upload", SheetId = 2, Id = relationshipId2 };

var suspenseSheets = new Sheets();
suspenseSheets.Append(sheetSuspense);
workbook.Append(suspenseSheets);

using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart;
                OpenXmlWriter writer;

                workbookPart = document.AddWorkbookPart();

                WorkbookStylesPart wbsp = workbookPart.AddNewPart<WorkbookStylesPart>();
                var excelStyleSheet = new ExcelStylesheet();

                // Cell formats
                excelStyleSheet.AddCellFormat("DateTime", (f) =>
                {
                    f.NumberFormatId = 14; //general
                    f.ApplyNumberFormat = BooleanValue.FromBoolean(true);
                });

                excelStyleSheet.AddCellFormat("Numeric", (f) =>
                {
                    f.NumberFormatId = 2; // 0.00
                    f.ApplyNumberFormat = BooleanValue.FromBoolean(true);
                });

                SharedStringTablePart stringTable = workbookPart.AddNewPart<SharedStringTablePart>();

                string XML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><sst xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main""></sst>";

                AddPartXml(stringTable, XML);

                var workbook = new Workbook();
                workbookPart.Workbook = workbook;

                var fileVersion = new FileVersion() { ApplicationName = "Microsoft Office Excel" };
                workbook.Append(fileVersion);

                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

                var relationshipId = workbookPart.GetIdOfPart(worksheetPart);
                var sheetPayment = new Sheet { Name = "Payment Upload", SheetId = 1, Id = relationshipId };

                var paymentSheets = new Sheets();
                paymentSheets.Append(sheetPayment);
                workbook.Append(paymentSheets);

                writer = OpenXmlWriter.Create(worksheetPart);

                writer.WriteStartElement(new Worksheet());
                writer.WriteStartElement(new SheetData());

                writer.WriteEndElement();      // SheetData

                var worksheetPart2 = workbookPart.AddNewPart<WorksheetPart>();
                var relationshipId2 = workbookPart.GetIdOfPart(worksheetPart2);
                var sheetSuspense = new Sheet { Name = "Suspense Upload", SheetId = 2, Id = relationshipId2 };

                var suspenseSheets = new Sheets();
                suspenseSheets.Append(sheetSuspense);
                workbook.Append(suspenseSheets);

                writer = OpenXmlWriter.Create(worksheetPart);

                writer.WriteStartElement(new Worksheet());
                writer.WriteStartElement(new SheetData());

                writer.WriteEndElement();      // SheetData

                writer.WriteEndElement();      // Worksheet

                writer.Close();

                wbsp.Stylesheet = excelStyleSheet.Stylesheet;
                wbsp.Stylesheet.Save();

                document.WorkbookPart.Workbook.Save();
                document.Close();
            }

How to copy a word document with images to another word ocument

$
0
0

Now, I'm facing a problem. I try to copy a word document that with images to a new word document. I use OpenXml SDK for C#. Who can help me? I have searched the Internet for a really long time, But no solution. I need help. Thanks very much for who help me.

How to get started writing Excel Addins?

$
0
0

So far, my only development experience is as follows:

(1) Have some artist generate a nice looking spreadsheet (just the top portion, with headers, logo, etc.).

(2) Use the OpenXML Productivity Tool to reflect that spreadsheet

(3) Write C# code to fill a number of rows immediately below the artist-created spreadsheet.

(4) Save the generated file.

The reason I mention this is to stress the fact that I am rather familiar with OpenXML coding to create standalone applications, but know nothing about creatingExcel Addins.

Two questions:

(a) What options does a developer have, for Addins?

(b) Let's say I want to leverage my experience with OpenXML, where should I point my browser?

Note: I am only interested in C#

TIA


How to insert the row in exisiting template in open xml

$
0
0
I have a scenario to generate the Excel sheet based on the existing template, pls refere the attached screen short, here i have two rows, but if i want to display the records in more than 2 ros then i want to insert the row dynamically, but i tried to do that, it's nto working, please any body help me to solve this problem
public void InsertRow(string sheetName,WorkbookPart wbPart, uint rowIndex)
        {
            Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where((s) => s.Name == sheetName).FirstOrDefault();

            if (sheet != null)
            {
                
                Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
                SheetData sheetData = ws.WorksheetPart.Worksheet.GetFirstChild<SheetData>();
                Row refRow = GetRow(sheetData, rowIndex);++rowIndex;
                Row newRow = new Row()
                {
                    RowIndex = rowIndex
                };
                sheetData.InsertAfter(newRow, refRow);
                //sheetData.InsertAfterSelf(refRow);
                ws.Save();
            }
        }

private Row GetRow(SheetData wsData, UInt32 rowIndex)
        {
            var row = wsData.Elements<Row>().
            Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
            if (row == null)
            {
                row = new Row();
                row.RowIndex = rowIndex;
                wsData.Append(row);
            }
            return row;
        }

 

Remove default text "Click here to enter text." from all content controls

$
0
0

Hi,

Whenever I add a content control inside Word 2010 document I see a default text "Click here to enter text.". I don't want my end users to see such text in the document. Is there a way to remove of disable this feature in Word 2010.

I am populating text into content controls in my document using OpenXml SDK. BUT wanted to know if there is a setting to disable this default text in content control. I can write code to remove this text through code but that's just a waste :(.  I have about 50 odd content controls in a document.

Regards,

Vijay

Wrong replacement in content controls

$
0
0

Hi Experts,

i have some Word-Documents with Plain-Text Content-Controls. Each one of them has a unique TAG to identify them later by code. In that code part i iterate over all Content Controls to see if the TAG matches my requirements. If so, some Text will be set. This is working fine but for one user some controls having the text value of another control in that document. e.g. The Control 'Worker' has the value of Control 'Deliverydate'. This happens ONLY to one specific user. The code component is having a verbose logger and i can clearly see that the correct values will be written to the controls.

So i think, there is something with the Client. Does anybody may run into the same issue?

Thanks, Ronny

How to keep the style when I rewrite table from html to excel

$
0
0

Now I am face the problem.

First I created a DataSet from a xlsx file. And I had to keep the style so I can display it on web.

Here is my code

        string GetText(string xml)
        {
            XDocument xdoc = XDocument.Parse(xml);
            XNamespace space = @"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            XElement element = xdoc.Element(space + "si");
            if (element == null) return "";
            StringBuilder sbText = new StringBuilder();
            string str = "";
            if (element.Element(space + "r") != null)
            {
                foreach (XElement xr in element.Elements(space + "r"))
                {
                    str = "";
                    if ((xr.Element(space + "t") != null))
                    {
                        str = xr.Element(space + "t").Value;
                        if (string.IsNullOrEmpty(str)) continue;
                        if (xr.Element(space + "rPr") != null)
                        {
                            XElement rpr = xr.Element(space + "rPr");
                            if (rpr.Element(space + "b") != null) str = "<b>" + str + "</b>";
                            if (rpr.Element(space + "u") != null) str = "<u>" + str + "</u>";
                            if (rpr.Element(space + "i") != null) str = "<i>" + str + "</i>";
                        }else if (xr.Element(space + "rpr") != null)
                        {
                            XElement rpr = xr.Element(space + "rpr");
                            if (rpr.Element(space + "b") != null) str = "<b>" + str + "</b>";
                            if (rpr.Element(space + "u") != null) str = "<u>" + str + "</u>";
                            if (rpr.Element(space + "i") != null) str = "<i>" + str + "</i>";
                        }
                    }
                    sbText.Append(str);
                }
            }
            else if (element.Element(space + "t") != null) return element.Element(space + "t").Value;
            return sbText.ToString();
        }

It work well. But This is not over. All the text I get is store as xml file.

This is the main work, Get message from xml file, and then rewrite it into a new xlsx file.

The problem is, How can I Keep the <b>,<u>,<i> style in the xlsx file.

Because the tag <b> or <i> or <u> in xlsx table is text, not style.

Excel Open Issue

$
0
0

Hi,

  I am using open xml to generate the invoice report in excel sheet, so i loaded invoice no(F2),  ship to(A13 to A18) and Sold to(D13 to D18) values, but when i open the excel sheet it throw the error message(Ref: Excel Problem1.png), and it's not loading the values in ship to and sold to address values. I could not able to guess what could be an issue, please help me to solve this issue. Please referee the attachment(Excel Problem.png), this is the template i am using in my sample application

Sample Code

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Report is creating");
            InvoiceReport productReport = new InvoiceReport("Commercial_Invoice_1");
            productReport.CreateReport();
            Console.WriteLine("Report is created");
            Console.WriteLine("Press Enter to close");
            Console.ReadLine();
        }
    }

InvoiceReport.cs

 public class InvoiceReport
    {

        string path = @"E:\SampleApplication\Excel\";
        string templateName = "Invoice.xlsx";
        WorkbookPart wbPart = null;
        SpreadsheetDocument document = null;
        HelperClass helperClass = null;
        InvoiceHeader invoiceHeader = null;
        private InvoiceInformation invoiceInformation = null;

        public InvoiceReport(string client)
        {
            helperClass = new HelperClass();
            invoiceHeader = new InvoiceHeader();
            invoiceInformation = new InvoiceInformation();

            LoadInvoiceHeader();
            string newFileName = path + client + ".xlsx";
            helperClass.CopyFile(path + templateName, newFileName);
            document = SpreadsheetDocument.Open(newFileName, true);
            wbPart = document.WorkbookPart;
        }

        public void CreateReport()
        {           
            
            string wsName = "Commercial Invoice";

            

            //Commercial Invoice
            helperClass.UpdateValue(wsName, "F2", invoiceInformation.InvoiceHeaderInfo.InvoiceNo, 0, true, wbPart);
            //helperClass.UpdateValue(wsName, "F7", "Date:"+invoiceInformation.InvoiceHeaderInfo.InvoiceDate.ToShortDateString(), 0, true, wbPart);
            helperClass.UpdateValue(wsName, "A13", invoiceInformation.InvoiceHeaderInfo.SoldToAddress1, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "A14", invoiceInformation.InvoiceHeaderInfo.SoldToAddress2, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "A15", invoiceInformation.InvoiceHeaderInfo.SoldToAddress3, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "A16", invoiceInformation.InvoiceHeaderInfo.SoldToAddress4, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "A17", invoiceInformation.InvoiceHeaderInfo.SoldToAddress5, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "D13", invoiceInformation.InvoiceHeaderInfo.ShipToAddress1, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "D14", invoiceInformation.InvoiceHeaderInfo.ShipToAddress2, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "D15", invoiceInformation.InvoiceHeaderInfo.ShipToAddress3, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "D16", invoiceInformation.InvoiceHeaderInfo.ShipToAddress4, 0, true, wbPart);
            helperClass.UpdateValue(wsName, "D17", invoiceInformation.InvoiceHeaderInfo.ShipToAddress5, 0, true, wbPart);

            
            
            document.Close();
        }

        private void LoadInvoiceHeader()
        {
            invoiceHeader = new InvoiceHeader();
            List<InvoiceDetail1> invoiceDetails1 = new List<InvoiceDetail1>();
            List<InvoiceDetail2> invoiceDetails2 = new List<InvoiceDetail2>();
            List<InvoiceDetail> invoiceDetails = new List<InvoiceDetail>();

            invoiceHeader.InvoiceNo = "480-200652";
            invoiceHeader.InvoiceDate = DateTime.Now;
            invoiceHeader.SoldToAddress1 = "Bahia";// Motors S.A.";
            invoiceHeader.SoldToAddress2 = "Apartado Postal 6-2286";
            invoiceHeader.SoldToAddress3 = "El Dorado";
            invoiceHeader.SoldToAddress4 = "Panama";
            invoiceHeader.SoldToAddress5 = "Rep. de Panama";
            invoiceHeader.ShipToAddress1 = "Bahia Motors S.A.";
            invoiceHeader.ShipToAddress2 = "Apartado Postal 6-2286";
            invoiceHeader.ShipToAddress3 = "El Dorado";
            invoiceHeader.ShipToAddress4 = "Panama";
            invoiceHeader.ShipToAddress5 = "Rep. de Panama";
            invoiceHeader.OriginPoint = "Alliston, OT";
            invoiceHeader.ShippedOn = DateTime.Now;
            invoiceHeader.PortOfLoading = "Jacksonville, FL";
            invoiceHeader.PlaceOfDelivery = "Manzanillo, Panama";
            invoiceHeader.ETA = DateTime.Now;
            invoiceHeader.ShippedVIA = "Ocean";
            invoiceHeader.Vessel = "BRUSSEL, V. 20";
            invoiceHeader.BillOfLading = "480-183-01";
            invoiceHeader.TermsOfPayment = "Net 60 Days";
            invoiceInformation.InvoiceHeaderInfo = invoiceHeader;

            invoiceDetails.Add(new InvoiceDetail()
            {
                InvoiceNo = "20H-2224-02",
                Quantity = 1,
                Description = "FB253EE KR CIVIC 4DR 1.8S 5MT",
                UnitPrice = 500,
                Amount = 500
            });

            invoiceDetails.Add(new InvoiceDetail()
            {
                InvoiceNo = "20H-2224-03",
                Quantity = 2,
                Description = "CR-V 5DR LX-C2WD 5AT",
                UnitPrice = 200,
                Amount = 400
            });

            invoiceDetails.Add(new InvoiceDetail()
            {
                InvoiceNo = "20H-2224-02",
                Quantity = 4,
                Description = "TAFFETA WHITE NH-578X",
                UnitPrice = 500,
                Amount = 2000
            });
            invoiceInformation.InvoiceDetails = invoiceDetails;
        }
}

HelperClass.cs

public class HelperClass
    {
public bool UpdateValue(string sheetName, string addressName, string value, UInt32Value styleIndex, bool isString, WorkbookPart wbPart)
        {
            // Assume failure.
            bool updated = false;

            Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where((s) => s.Name == sheetName).FirstOrDefault();

            if (sheet != null)
            {
                Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
                Cell cell = InsertCellInWorksheet(ws, addressName);

                if (isString)
                {
                    // Either retrieve the index of an existing string,
                    // or insert the string into the shared string table
                    // and get the index of the new item.
                    int stringIndex = InsertSharedStringItem(wbPart, value);

                    cell.CellValue = new CellValue(stringIndex.ToString());
                    //cell.CellValue = new CellValue(value);
                    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);

                    /*cell.DataType = CellValues.InlineString;
                    cell.InlineString = new InlineString() { Text = new Text(value) };*/
                }
                else
                {
                    cell.CellValue = new CellValue(value);
                    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                }

                if (styleIndex > 0)
                    cell.StyleIndex = styleIndex;

                // Save the worksheet.
                ws.Save();
                updated = true;
            }

            return updated;
        }


private Cell InsertCellInWorksheet(Worksheet ws, string addressName)
        {
            SheetData sheetData = ws.GetFirstChild<SheetData>();
            Cell cell = null;

            UInt32 rowNumber = GetRowIndex(addressName);
            Row row = GetRow(sheetData, rowNumber);
            

            // If the cell you need already exists, return it.
            // If there is not a cell with the specified column name, insert one.  
            Cell refCell = row.Elements<Cell>().
                Where(c => c.CellReference.Value == addressName).FirstOrDefault();
            if (refCell != null)
            {
                cell = refCell;
            }
            else
            {
                cell = CreateCell(row, addressName);
            }
            return cell;
        }

}

ExcelProblem.png

Error Message

Error Message

Viewing all 1288 articles
Browse latest View live


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