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

XML to MS Word Using C#.NET

$
0
0

Hi,

I have a requirement where i need to use a XML to convert it to any Word(2003/2007 either doc or docx) format with some custom styles using XSLT. Anyone has suggestions or reference links to start this? Aprreciate your help.

-Bhaskar.


SmartArt diagram - changing the text style

$
0
0

I hope this is the right place for this question.

I've successfully modified a SmartArt diagram (horizontal picture list) by changing the shape, border and fill settings. Where I'm stuck is changing the text style from plain to bold.

I've edited table styles to include bold text in the past without a problem but nothing I try with SmartArt has any effect.

Can anyone point me in the right direction?

Styles in Excel using Open XML

$
0
0

Hey folks,

I am quite new to C# & got stuck with a problem.

I am trying to add some style to the Excel using OpenXML, though it is not drawing borders, the fills (foreground & background colors) and alignment to the cells. I tried many times with different ways, though I am not able to do so.
The following code is not generating any error. Compiling successfully, however not giving the expected output.

I regret I am not able to put up the screenshots of actual output & expected output, due to account limitation initially.

The requirement is that only the top row to have this specific style, how can I achieve it?

Any guidance would be greatly appreciated.

Code snippet:

private void ExportDataSet()
{
WorkbookStylesPart wbsp = workbookPart.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
}

private static DocumentFormat.OpenXml.Spreadsheet.Stylesheet CreateStylesheet()
{
DocumentFormat.OpenXml.Spreadsheet.Stylesheet stylesheet1 = new DocumentFormat.OpenXml.Spreadsheet.Stylesheet();

#region Font
DocumentFormat.OpenXml.Spreadsheet.Fonts fonts = new DocumentFormat.OpenXml.Spreadsheet.Fonts() { Count = (DocumentFormat.OpenXml.UInt32Value)2U};

// FontID = 0 (The Default Font)
DocumentFormat.OpenXml.Spreadsheet.Font font0 = new DocumentFormat.OpenXml.Spreadsheet.Font();
DocumentFormat.OpenXml.Spreadsheet.FontSize fontSize0 = new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 11D };
DocumentFormat.OpenXml.Spreadsheet.Color color0 = new DocumentFormat.OpenXml.Spreadsheet.Color() { Theme = (DocumentFormat.OpenXml.UInt32Value)1U };
DocumentFormat.OpenXml.Spreadsheet.FontName fontName0 = new DocumentFormat.OpenXml.Spreadsheet.FontName() { Val = "Calibri" };

font0.Append(fontSize0);
font0.Append(color0);
font0.Append(fontName0);

// FontID = 1
DocumentFormat.OpenXml.Spreadsheet.Font font1 = new DocumentFormat.OpenXml.Spreadsheet.Font();
DocumentFormat.OpenXml.Spreadsheet.FontSize fontSize1 = new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 12D };
DocumentFormat.OpenXml.Spreadsheet.FontName fontName1 = new DocumentFormat.OpenXml.Spreadsheet.FontName() { Val = "Calibri" };
DocumentFormat.OpenXml.Spreadsheet.Color color1 = new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = new DocumentFormat.OpenXml.HexBinaryValue("5B9BD5") };
DocumentFormat.OpenXml.Spreadsheet.Bold bold1 = new DocumentFormat.OpenXml.Spreadsheet.Bold() { Val = true };

// Foreground & Background not working
DocumentFormat.OpenXml.Spreadsheet.ForegroundColor foregroundColor1 = new DocumentFormat.OpenXml.Spreadsheet.ForegroundColor() { Rgb = new DocumentFormat.OpenXml.HexBinaryValue("FF00FF00") };
DocumentFormat.OpenXml.Spreadsheet.BackgroundColor backgroundColor1 = new DocumentFormat.OpenXml.Spreadsheet.BackgroundColor() { Rgb = new DocumentFormat.OpenXml.HexBinaryValue("FF00FF00") };


font1.Append(fontSize1);
font1.Append(fontName1);
font1.Append(color1);
font1.Append(bold1);
font1.Append(foregroundColor1);
font1.Append(backgroundColor1);

fonts.Append(font1);

int fontIndex = fonts.Count() - 1;
#endregion

#region CellBorders
DocumentFormat.OpenXml.Spreadsheet.Borders borders = new DocumentFormat.OpenXml.Spreadsheet.Borders() { Count = (DocumentFormat.OpenXml.UInt32Value)2U };

// Border ID = 0 (The Default Border)
DocumentFormat.OpenXml.Spreadsheet.Border border0 = new DocumentFormat.OpenXml.Spreadsheet.Border();

DocumentFormat.OpenXml.Spreadsheet.LeftBorder leftBorder0 = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder();
DocumentFormat.OpenXml.Spreadsheet.RightBorder rightBorder0 = new DocumentFormat.OpenXml.Spreadsheet.RightBorder();
DocumentFormat.OpenXml.Spreadsheet.TopBorder topBorder0 = new DocumentFormat.OpenXml.Spreadsheet.TopBorder();
DocumentFormat.OpenXml.Spreadsheet.BottomBorder bottomBorder0 = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder();

border0.Append(leftBorder0);
border0.Append(rightBorder0);
border0.Append(topBorder0);
border0.Append(bottomBorder0);

// Border ID = 1
DocumentFormat.OpenXml.Spreadsheet.Border border1 = new DocumentFormat.OpenXml.Spreadsheet.Border();

DocumentFormat.OpenXml.Spreadsheet.LeftBorder leftBorder = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder() { Style = DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick };
DocumentFormat.OpenXml.Spreadsheet.RightBorder rightBorder = new DocumentFormat.OpenXml.Spreadsheet.RightBorder() { Style = DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick };
DocumentFormat.OpenXml.Spreadsheet.TopBorder topBorder = new DocumentFormat.OpenXml.Spreadsheet.TopBorder() { Style = DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick };
DocumentFormat.OpenXml.Spreadsheet.BottomBorder bottomBorder = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder() { Style = DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick };

border1.Append(leftBorder);
border1.Append(rightBorder);
border1.Append(topBorder);
border1.Append(bottomBorder);

borders.Append(border1);

int borderIndex = borders.Count() - 1;
#endregion

#region Fill
DocumentFormat.OpenXml.Spreadsheet.Fills fills = new DocumentFormat.OpenXml.Spreadsheet.Fills() { Count = (DocumentFormat.OpenXml.UInt32Value)3U };

// Fill ID = 0 (The Default Fill)
DocumentFormat.OpenXml.Spreadsheet.Fill fill0 = new DocumentFormat.OpenXml.Spreadsheet.Fill();
DocumentFormat.OpenXml.Spreadsheet.PatternFill patternFill0 = new DocumentFormat.OpenXml.Spreadsheet.PatternFill() { PatternType = DocumentFormat.OpenXml.Spreadsheet.PatternValues.None };     // required, reserved by Excel
fill0.Append(patternFill0);

// Fill ID = 1 (The default fill of Gray)
DocumentFormat.OpenXml.Spreadsheet.Fill fill1 = new DocumentFormat.OpenXml.Spreadsheet.Fill();
DocumentFormat.OpenXml.Spreadsheet.PatternFill patternFill1 = new DocumentFormat.OpenXml.Spreadsheet.PatternFill() { PatternType = DocumentFormat.OpenXml.Spreadsheet.PatternValues.Gray125 };  // required, reserved by Excel
fill1.Append(patternFill1);

// Fill ID = 2
DocumentFormat.OpenXml.Spreadsheet.Fill fill2 = new DocumentFormat.OpenXml.Spreadsheet.Fill();
DocumentFormat.OpenXml.Spreadsheet.PatternFill patternFill2 = new DocumentFormat.OpenXml.Spreadsheet.PatternFill() { PatternType = DocumentFormat.OpenXml.Spreadsheet.PatternValues.Solid };    // customized Pattern value
DocumentFormat.OpenXml.Spreadsheet.ForegroundColor foregroundColorFill2 = new DocumentFormat.OpenXml.Spreadsheet.ForegroundColor() { Rgb = new DocumentFormat.OpenXml.HexBinaryValue("FF00FF00") };
DocumentFormat.OpenXml.Spreadsheet.BackgroundColor backgroundColorFill2 = new DocumentFormat.OpenXml.Spreadsheet.BackgroundColor() { Rgb = new DocumentFormat.OpenXml.HexBinaryValue("5B9BD500") };

patternFill2.Append(foregroundColorFill2);
patternFill2.Append(backgroundColorFill2);
fill2.Append(patternFill2);

fills.Append(fill2);

int fillIndex = fills.Count() - 1;
#endregion

#region Alignment
DocumentFormat.OpenXml.Spreadsheet.Alignment alignment = new DocumentFormat.OpenXml.Spreadsheet.Alignment()
{
Horizontal = DocumentFormat.OpenXml.Spreadsheet.HorizontalAlignmentValues.Left,
Vertical = DocumentFormat.OpenXml.Spreadsheet.VerticalAlignmentValues.Center
};
#endregion

#region Cell Style Formats & Cell Formats
DocumentFormat.OpenXml.Spreadsheet.CellFormats cellFormats0 = new DocumentFormat.OpenXml.Spreadsheet.CellFormats() { Count = (DocumentFormat.OpenXml.UInt32Value)1U };

// Cell Format ID = 0 (The Default Cell Format)
DocumentFormat.OpenXml.Spreadsheet.CellFormat cellFormat0 = new DocumentFormat.OpenXml.Spreadsheet.CellFormat()
{
NumberFormatId = (DocumentFormat.OpenXml.UInt32Value)0U,
FontId = (DocumentFormat.OpenXml.UInt32Value)0U,
FillId = (DocumentFormat.OpenXml.UInt32Value)0U,
BorderId = (DocumentFormat.OpenXml.UInt32Value)0U,
FormatId = (DocumentFormat.OpenXml.UInt32Value)0U
};

cellFormats0.Append(cellFormat0);

// Cell Format ID = 1
DocumentFormat.OpenXml.Spreadsheet.CellFormat cellFormat1 = new DocumentFormat.OpenXml.Spreadsheet.CellFormat()
{
NumberFormatId = (DocumentFormat.OpenXml.UInt32Value)1U,
FontId = (DocumentFormat.OpenXml.UInt32Value)1U,
FillId = (DocumentFormat.OpenXml.UInt32Value)2U,
BorderId = (DocumentFormat.OpenXml.UInt32Value)1U,
FormatId = (DocumentFormat.OpenXml.UInt32Value)1U,
ApplyBorder = true,
ApplyFont = true,
ApplyFill = true,
};
cellFormats0.Append(cellFormat1);

DocumentFormat.OpenXml.Spreadsheet.CellStyles cellStyles = new DocumentFormat.OpenXml.Spreadsheet.CellStyles() { Count = (DocumentFormat.OpenXml.UInt32Value)1U };
DocumentFormat.OpenXml.Spreadsheet.CellStyle cellStyle = new DocumentFormat.OpenXml.Spreadsheet.CellStyle()
{
Name = "Normal",
FormatId = (DocumentFormat.OpenXml.UInt32Value)0U,
BuiltinId = (DocumentFormat.OpenXml.UInt32Value)1U
};

cellStyles.Append(cellStyle);
#endregion

#region Stylesheet
stylesheet1.Append(fonts);
stylesheet1.Append(fills);
stylesheet1.Append(borders);
stylesheet1.Append(cellFormats0);
stylesheet1.Append(cellStyles);
#endregion

return stylesheet1;
}

Fill an Excel Table using Open XML SDK 2.0

$
0
0

Hello experts,

I have just started using Open XML SDK 2.0 to write data in Excel (.xlsx) file. I am trying to fill with data into an existing file that contains an Excel Table (Table1) in the first sheet and a Pivot Table in a separate sheet (Sheet2) using the Table (Table1) from the first Sheet (Sheet1).

The template is created manually using Microsoft Office Excel 2007 application. The Table in the first sheet and the pivot table in the second sheet are also created using this. The Table (Table1) contains only one row for the column headers. My application should insert records in the table using Open XML SDK 2,0 and stretch the table to the number of rows inserted.

When I insert the records from second row in the first sheet, the table does not get stretched to the total number of rows. So the pivot table is also not showing any records when I refresh due to this, although the first sheet contains all the rows.

Can anyone please help me writing the correct code to insert records in the main table in the first sheet that will allow the pivot table refresh properly?

Thanks in advance...

-Jahedur Rahman

SpreadsheetDocument.CreateFromTemplate Examples

$
0
0

Hi,

Are there any examples of the usage of SpreadsheetDocument.CreateFromTemplate() ?  Is this meant to be from an xltx template file? When i try to open from excel it gives me the error "Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.  

Basically, i want to have a template with all the formatting and formulas included in the template and then just populate my dataset into it.

I have the code below:

SpreadsheetDocument doc = SpreadsheetDocument.CreateFromTemplate(templateFilePath);

doc.WorkbookPart.Workbook.Save();

analyzerDoc.SaveAs(outputFileName);

doc.Close();
Update: in an effort to deduce the problem, i was analyzing the xml files by changing the xlsx to a zip, when i change the zip back to an xslx, the file opens properly by excel.  


Embedded fonts -

$
0
0

Hi,

Is it possible to use embedded fonts used in presentation directly in web browser ?

After creating a zip the embedded font's are coming as font1.fntdata. 

IE can understand this but other browsers are not able to render this file. Can you please suggest how can it be possible to convert .fntdata to woff/ttf ?

Thanks,

Vishal Sood

How to read VBA code from macro-enabled document(.DOCM) using openXML in C# ?

$
0
0

I need to read VBA code which is included in macro enabled document(.DOCM) file using openXML in c#.

I have tried following code but it returns weird string.

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
{

       VbaProjectPart vbaPart = wordDoc.MainDocumentPart.VbaProjectPart;

       Stream stream = vbaPart.GetStream();

       using(StreamReader reader = new StreamReader(stream,Encoding.UTF8))

      {

          string vbaData = reader.ReadToEnd();

      }

}

Any help would be appreciated.

Thanks!

Removing Embedded Fonts

$
0
0

Hey,

I was looking for a way to remove one or more embedded fonts within a document. Is this possible? I figured I could set the font table to null, but I'd imagine the fonts will still be in the file itself.

Help would be appreciated!


Embedded fonts - .fntdata

$
0
0
Hi there,
I found embedded font (.fntdata) in PowerPoint XML. These types of font work only in internet explorer.
<html><head><title>Embedded Font</title><styletype="text/css">@font-face{font-family: Chiller;src:url('font1.fntdata');}.Chiller{font-family: Chiller;font-size:60px;color:#000;}</style></head><body><divclass="Chiller">Embedded Font</div></body></html>
Is there any way or any type of conversion(TTF, WOFF) to run (.fntdata) in all browsers.
Any help would be appreciated.
Best Regards
Sumit Bhatia

OpenXML SDK 2.5 Excel File Corruption

$
0
0

I've come across a problem in using the OpenXML SDK 2.5 where the spreadsheet cannot be opened without losing data when you fill cells past column z (all on the same row). The Issue is that in the xml for the sheet, column references AA, AB, AC, etc sort BEFORE column B in the cell list. The consequence of this is that the data for cells A, AA, AB, AC, etc is written, but the data for the cells B to Z is stripped out of the recovered spreadsheet.

Create a blank spreadsheet (.xlsx), and, using the SDK, put data into cells A1, B1, C1, AA1, AB1, AC1. Save the file.

Try to open the spreadsheet in excel and receive the message that the file is essentially corrupt. Recover the spreadsheet and see that there is data in cells A1, AA1, AB1 and AC1, but that in B1 and C1 is missing.

If you go into the xml internals of the spreadsheet and move the structures for cells AA and beyond to after that for column C (in this case) and then reopen the file, it's fine.

I am currently working around this by starting my spreadsheet in column AA.

Mike

Write to excel file using open xml and powershell

$
0
0

Hello Experts,

We are planning to automate some of the tasks at server side where MS Office is not installed. Hence we have installed Open XML SDK. Unfortunately I didn't find any helpful leads to read/write excel files using open XML & PowerShell.

I really appreciate any help on this regard.

Regards,

C# OpenXML for reading Microsoft Excel comments

$
0
0
I am running the latest Office 365 Excel version, 1901. I have updated to the latest OpenXml SDK nuget package but am unable to figure out how to programmatically read information about threaded comments, as all I'm seeing is a full summary comment. Even using the latest OpenXml Nuget package. If I convert the Excel document to a .zip file, I can see "threadedComments.xml" files which has what I need, but do not know how to get to it programmatically in C# .NET. Thank you!

"There's many ways to code a solution. But only a few right ways." -http://www.isallstars.com


C# clear "styles.xml" in the book excel (xlsx) using closedxml

$
0
0
I have a program (C#) which inserts values and applies styles to the book excel (xlsx)
I use the library closedxml 
I ran into the problem that after many times file entries (xlsx), the style of the book does not apply.
I noticed that the file size increases over time when I changed the file extension. (xlsx) on zip and unzipped it noticed that the file "styles.xml" is large in size 8 - 10 MB.
яI think that the reason for the file overflow "styles.xml".
How to clean using closedxml all previously applied styles in the book excel? 

Copying slides between presentations and applying destination presentations master part

$
0
0
We are copying slides from one presentation to another using logic given at http://msdn.microsoft.com/en-us/library/office/ee361883(v=office.12).aspx. This adds a new slide master part for every slide from the source. Instead we want to be able to add slides and inherit the slide master of the destination presentation just as it happens when we copy and paste the slide manually. We should also be add the slide layout part of source slide if does not already exist in the destination slide master. Any pointers would be really helpful.

Insert text into a table cell in PPTX file using Open XML SDK

$
0
0
Hi, I have a Power Point template which has a table in it. I want to place some text in a specific cell of that table using C#. Can anyone suggest me some code.

error MSB4044: The "GetAssemblyVersion" task was not given a value for the required parameter "NuGetVersion"

$
0
0

Hi,

After download the source code from GitHub, I got an error when I build the solution:

C:\Program Files\dotnet\sdk\2.2.104\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.GenerateAssemblyInfo.targets(161,5): error MSB4044: The "GetAssemblyVersion" task was not given a value for the required parameter "NuGetVersion".

My OS: win10

Visual Stuido 2017 version 15.9.7

Does anyone meet this error? And how to solve it?

Thanks.

Jason_Shinetech

MemoryStream and WordprocessingDocument

$
0
0

Hi Everyone, 

 I have a problem when using the WordProcessingDocument object together with a MemoryStream object. 

 My code is the following. 

MemoryStream stream = new MemoryStream(loanDocumentViewModel.DocumentContent);

            //using (MemoryStream stream = new MemoryStream(data)) //;MemoryStream ms = new MemoryStream(dc.DocumentContent))
            //{
            using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
            //using (WordprocessingDocument doc = WordprocessingDocument.Open(@"Documents\OtherDocuments\copy.docx", true))
            {

              DocumentSettingsPart docSett = doc.MainDocumentPart.DocumentSettingsPart;
                docSett.RootElement.Append(new DocumentProtection { Edit = DocumentProtectionValues.ReadOnly });
                docSett.RootElement.Save();

                doc.MainDocumentPart.Document.Save();
            }

The dc.DocumentContent is a Array readed from a Database. 

When I save my object into the Database again and open it. 

   Word is telling me that the file is corrupt, but It can be opened. 

Any clues on what wrong with the code?

I have tried to do the same operation, with a plain file and that works perfectly. 

Best Regards

  Lars 

VmlDrawingPart is empty in an OpenXml Document spreadsheet

$
0
0

Hello,

I am attempting to edit an Excel document via OpenXml. I have almost everything working. <g class="gr_ gr_255 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Punctuation only-ins replaceWithoutSep" data-gr-id="255" id="255">Basically</g> I am inserting data into Cells and inserting rows. 

I have <g class="gr_ gr_300 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del" data-gr-id="300" id="300">check boxes</g> below the rows I am inserting so I need to update their positioning. I found the part of the vmlDrawing1.xml that I need to update, but when I look at the DOM that part doesn't exist.

Here is my console app to test what I want to do:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApp1
{
    public class ExcelDataWriter
    {
        static void Main(string[] args)
        {
            var modifications = new List<ExcelDataModification>
            {
                new ExcelDataModification()
                {
                    Row = 4,
                    CellId = "A",
                    CellValue = "2/25/2019",
                },

                new ExcelDataModification()
                {
                    Row = 4,
                    CellId = "E",
                    CellValue = "1234-1234",
                },

                new ExcelDataModification()
                {
                    Row = 6,
                    CellId = "A",
                    CellValue = "Customer Name",
                },

                new ExcelDataModification()
                {
                    Row = 8,
                    CellId = "H",
                    CellValue = "County",
                },

                new ExcelDataModification()
                {
                    Row = 10,
                    CellId = "A",
                    CellValue = "Address 1, address 2",
                },

                new ExcelDataModification()
                {
                    Row = 10,
                    CellId = "H",
                    CellValue = "City, MN",
                },

                new ExcelDataModification()
                {
                    Row = 15,
                    CellId = "B",
                    CellValue = "1",
                    DataType = CellValues.Boolean,
                },

                new ExcelDataModification()
                {
                    Row = 16,
                    CellId = "B",
                    CellValue = "0",
                    DataType = CellValues.Boolean,
                },

                new ExcelDataModification()
                {
                    Row = 17,
                    CellId = "B",
                    CellValue = "1",
                    DataType = CellValues.Boolean,
                },

                new ExcelDataModification()
                {
                    Row = 19,
                    CellId = "A",
                    CellValue = "Chad Clark",
                },

                new ExcelDataModification()
                {
                    Row = 19,
                    CellId = "D",
                    CellValue = "1234567",
                },

                new ExcelDataModification()
                {
                    Row = 19,
                    CellId = "E",
                    CellValue = "218-123-4567",
                },

                new ExcelDataModification()
                {
                    Row = 19,
                    CellId = "H",
                    CellValue = "chad@protech.com",
                },

                new ExcelDataModification()
                {
                    Row = 21,
                    CellId = "A",
                    //TODO Fix addresses
                    CellValue = "1234 Overthere St, City",
                },

                new ExcelDataModification()
                {
                    Row = 21,
                    CellId = "H",
                    CellValue = "MN",
                },

                new ExcelDataModification()
                {
                    Row = 21,
                    CellId = "I",
                    CellValue = "55660",
                },

                new ExcelDataModification()
                {
                    Row = 23,
                    CellId = "H",
                    CellValue = "2/24/2019",
                },
            };

            var rowItems = new List<List<ExcelDataModification>>();
            for(int i = 0; i < 10; i++)
            {
                rowItems.Add(new List<ExcelDataModification>()
                {
                    new ExcelDataModification()
                    {
                        CellId = "A",
                        CellValue = $"Location{i}",
                    },

                    new ExcelDataModification()
                    {
                        CellId = "C",
                        CellValue = $"Super, really long violation description that wraps into the next row, need to make sure it can handle this",
                    },
                });
            }

            new ExcelDataWriter().Create(modifications, rowItems);

            /*var workbook = new Spire.Xls.Workbook();
            workbook.LoadFromFile(@"C:\Source\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2\InspectionReportTemplate out.xlsx");
            workbook.SaveToFile("sample.pdf", Spire.Xls.FileFormat.PDF);*/
        }

        private List<string> sharedStrings = new List<string>();

        public void Create(List<ExcelDataModification> modifications, List<List<ExcelDataModification>> rowItemsList)
        {
            modifications = modifications.OrderBy(x => x.Row).ToList();

            File.Copy(@"C:\Source\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2\InspectionReportTemplate.xlsx",
                @"C:\Source\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2\InspectionReportTemplate out.xlsx", true);

            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(@"C:\Source\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2\InspectionReportTemplate out.xlsx", true);
            WorksheetPart worksheetPart = spreadsheetDocument.WorkbookPart.Parts.FirstOrDefault(x => x.OpenXmlPart is WorksheetPart).OpenXmlPart as WorksheetPart;
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

            //TODO spreadsheetDocument.WorkbookPart.WorkbookStylesPart

            var sharedStringTable = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable;
            //TODO - come up with something better
            foreach (var ssi in sharedStringTable.Elements<SharedStringItem>())
            {
                sharedStrings.Add(ssi.Text?.Text);
            }

            ApplyModifications(sheetData, modifications);

            AddRows(worksheetPart, 10);

            InsertData(sheetData, rowItemsList);

            for(int i = sharedStringTable.Count(); i < sharedStrings.Count; i++)
            {
                sharedStringTable.Append(new SharedStringItem(new Text(sharedStrings[i])));
            }

            uint diff = sharedStringTable.Count.Value - sharedStringTable.UniqueCount.Value;
            sharedStringTable.Count.Value = (uint)sharedStrings.Count;
            sharedStringTable.UniqueCount.Value = sharedStringTable.Count.Value - diff;

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

        }

        private const int startRowIndex = 13;

        private void ApplyModifications(SheetData sheetData, List<ExcelDataModification> modifications)
        {
            int i = 0;
            foreach (var rowElement in sheetData.ChildElements)
            {
                Row row = rowElement as Row;
                while (i < modifications.Count && row?.RowIndex == modifications[i].Row)
                {
                    EditCell(row, modifications[i++]);
                }
            }
        }

        private void InsertData(SheetData sheetData, List<List<ExcelDataModification>> rowItemsList)
        {
            for(int i = 0; i < rowItemsList.Count; i++)
            {
                Row row = sheetData.Elements<Row>().FirstOrDefault(x => x.RowIndex.Value == (uint)(startRowIndex + i));
                foreach (var rowItem in rowItemsList[i])
                {
                    EditCell(row, rowItem);
                }
            }
        }

        private void AddRows(WorksheetPart worksheetPart, uint numberOfRows)
        {
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

            //Move all of the rows down.
            foreach (var row in sheetData.Elements<Row>())
            {
                if(row.RowIndex > startRowIndex)
                {
                    row.RowIndex = new UInt32Value(row.RowIndex.Value + numberOfRows);
                    foreach(var cell in row.Elements<Cell>())
                    {
                        cell.CellReference = cell.CellReference.Value[0] + row.RowIndex.Value.ToString();
                    }
                }
            }

            //Duplicate startingRow into added rows
            Row startingRow = sheetData.Elements<Row>().First(x => x.RowIndex == startRowIndex);
            Row currentRow = startingRow;
            MergeCells mergeCells = worksheetPart.Worksheet.Descendants<MergeCells>().First();
            for(int i = 1; i <= numberOfRows; i++)
            {
                Row clonedRow = (Row)startingRow.CloneNode(true);
                clonedRow.RowIndex = (uint)(i + startRowIndex);
                //Call ToList to get a copy of the enumerator so we aren't modifying it in the middle of the enumeration with the ReplaceChild.
                foreach (var currentCell in clonedRow.Elements<Cell>().ToList())
                {
                    var cloneCell = (Cell)currentCell.CloneNode(true);
                    cloneCell.CellReference = cloneCell.CellReference.Value.Replace(startRowIndex.ToString(), clonedRow.RowIndex);

                    //TODO add even / odd extension method
                    if (clonedRow.RowIndex.Value % 2 == 0)
                    {
                        //clear cell
                        cloneCell.StyleIndex = 34;
                    }
                    else
                    {
                        //Grey cell
                        cloneCell.StyleIndex = 25;
                    }

                    clonedRow.ReplaceChild(cloneCell, currentCell);
                }

                //Duplicate merged cells
                foreach (var mergeCell in mergeCells.Elements<MergeCell>().Where(x => x.Reference.Value.Contains(startRowIndex.ToString())))
                {
                    var clonedMergeCell = (MergeCell)mergeCell.CloneNode(true);
                    clonedMergeCell.Reference.Value = clonedMergeCell.Reference.Value.Replace(startRowIndex.ToString(), clonedRow.RowIndex);
                    mergeCells.Append(clonedMergeCell);
                }

                currentRow.InsertAfterSelf(clonedRow);
                currentRow = clonedRow;
            }

            //Move the drawing content
            foreach (var markerType in worksheetPart.Worksheet.Descendants<MarkerType>())
            {
                if (int.Parse(markerType.RowId.Text) >= startRowIndex)
                {
                    markerType.RowId = new DocumentFormat.OpenXml.Drawing.Spreadsheet.RowId((int.Parse(markerType.RowId.Text) + numberOfRows).ToString());
                }
            }

            foreach (var markerType in worksheetPart?.DrawingsPart?.WorksheetDrawing?.Descendants<DocumentFormat.OpenXml.Drawing.Spreadsheet.MarkerType>())
            {
                if (int.Parse(markerType.RowId.Text) >= startRowIndex)
                {
                    markerType.RowId = new DocumentFormat.OpenXml.Drawing.Spreadsheet.RowId((int.Parse(markerType.RowId.InnerText) + numberOfRows).ToString());
                }
            }

            // Anchoe
            // From (upper right coordinate of a rectangle)
            // [0] Left column
            // [1] Left column offset
            // [2] Left row
            // [3] Left row offset
            // To (bottom right coordinate of a rectangle)
            // [4] Right column
            // [5] Right column offset
            // [6] Right row
            // [7] Right row offset

            
            foreach (var part in worksheetPart?.VmlDrawingParts)
            {
                //part is empty, has no parts or children
                VmlDrawingPart vmlDrawingPart = part as VmlDrawingPart;
            }

            foreach (var controlProperty in worksheetPart.ControlPropertiesParts)
            {
                //TODO - write code to get the integer part and deal with less than starting row index stuff.
                controlProperty.FormControlProperties.FmlaLink.Value = controlProperty.FormControlProperties.FmlaLink.Value[0] + (int.Parse(controlProperty.FormControlProperties.FmlaLink.Value.Substring(1)) + numberOfRows).ToString();
            }
        }

        private void EditCell(Row row, ExcelDataModification modification)
        {
            uint rowIndex = (uint)modification.Row;
            if (modification.Row == 0)
            {
                rowIndex = row.RowIndex.Value;
            }

            Cell cell;
            if (row.FirstOrDefault(x => (x as Cell)?.CellReference == $"{modification.CellId}{rowIndex}") is Cell existingCell)
            {
                cell = existingCell;
            }
            else
            {
                cell = new Cell()
                {
                    CellReference = $"{modification.CellId}{rowIndex}",
                };

                row.InsertBefore(cell, row.FirstChild);
            }

            if (modification.DataType.HasValue)
            {
                cell.DataType = modification.DataType.Value;
                cell.CellValue = new CellValue(modification.CellValue);
            }
            else
            {
                cell.DataType = CellValues.SharedString;
                int index = sharedStrings.IndexOf(modification.CellValue);
                if (index == -1)
                {
                    index = sharedStrings.Count;
                    sharedStrings.Add(modification.CellValue);
                }

                cell.CellValue = new CellValue(index.ToString());

            }
        }

        public class ExcelDataModification
        {
            public int Row { get; set; }
            public string CellId { get; set; }
            public string CellValue { get; set; }
            public CellValues? DataType { get; set; }
        }
    }
}


if you search it for this code: 

            foreach (var part in worksheetPart?.VmlDrawingParts)
            {
                //part is empty, has no parts or children
                VmlDrawingPart vmlDrawingPart = part as VmlDrawingPart;
            }


This is where I would expect to find my data.  <g class="gr_ gr_909 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Grammar multiReplace" data-gr-id="909" id="909">My spreadsheet</g> that I am using can be downloaded from Click here to download

This is the excerpt from the vmldrawing1.xml

<xml xmlns:v="urn:schemas-microsoft-com:vml"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout><v:shapetype id="_x0000_t201" coordsize="21600,21600" o:spt="201"
   path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path shadowok="f" o:extrusionok="f" strokeok="f" fillok="f" o:connecttype="rect"/><o:lock v:ext="edit" shapetype="t"/></v:shapetype><v:shape id="_x0000_s1029" type="#_x0000_t201" style=';
  margin-left:74pt;margin-top:250pt;width:21.5pt;height:15.5pt;z-index:1;
  mso-wrap-style:tight' filled="f" fillcolor="window [65]" stroked="f"
   strokecolor="windowText [64]" o:insetmode="auto"><v:path shadowok="t" strokeok="t" fillok="t"/><o:lock v:ext="edit" rotation="t"/><v:textbox style='mso-direction-alt:auto' o:singleclick="f"><div style='text-align:left'></div></v:textbox><x:ClientData ObjectType="Checkbox"><x:SizeWithCells/><x:Anchor>
        1, 52, 13, 20, 1, 95, 14, 27</x:Anchor><x:AutoFill>False</x:AutoFill><x:AutoLine>False</x:AutoLine><x:TextVAlign>Center</x:TextVAlign><x:FmlaLink>B15</x:FmlaLink><x:NoThreeD/></x:ClientData></v:shape><v:shape id="_x0000_s1030" type="#_x0000_t201" style=';
  margin-left:74pt;margin-top:262pt;width:21.5pt;height:15.5pt;z-index:2;
  mso-wrap-style:tight' filled="f" fillcolor="window [65]" stroked="f"
  strokecolor="windowText [64]" o:insetmode="auto"><v:path shadowok="t" strokeok="t" fillok="t"/><o:lock v:ext="edit" rotation="t"/><v:textbox style='mso-direction-alt:auto' o:singleclick="f"><div style='text-align:left'></div></v:textbox><x:ClientData ObjectType="Checkbox"><x:SizeWithCells/><x:Anchor>
        1, 52, 14, 20, 1, 95, 15, 22</x:Anchor><x:AutoFill>False</x:AutoFill><x:AutoLine>False</x:AutoLine><x:TextVAlign>Center</x:TextVAlign><x:FmlaLink>B16</x:FmlaLink><x:NoThreeD/></x:ClientData></v:shape><v:shape id="_x0000_s1031" type="#_x0000_t201" style=';
  margin-left:74pt;margin-top:276.5pt;width:21.5pt;height:15.5pt;z-index:3;
  mso-wrap-style:tight' filled="f" fillcolor="window [65]" stroked="f"
  strokecolor="windowText [64]" o:insetmode="auto"><v:path shadowok="t" strokeok="t" fillok="t"/><o:lock v:ext="edit" rotation="t"/><v:textbox style='mso-direction-alt:auto' o:singleclick="f"><div style='text-align:left'></div></v:textbox><x:ClientData ObjectType="Checkbox"><x:SizeWithCells/><x:Anchor>
        1, 52, 15, 20, 1, 95, 16, 22</x:Anchor><x:AutoFill>False</x:AutoFill><x:AutoLine>False</x:AutoLine><x:TextVAlign>Center</x:TextVAlign><x:FmlaLink>B17</x:FmlaLink><x:NoThreeD/></x:ClientData></v:shape></xml>

I need to update the anchor positioning to increment it for the number of rows I inserted.

Thank you for any assistance.

Hide Column in Excel using OpenXML

$
0
0

Hi Everyone,

I am am opening Excel file using OpenXML SDK. In my Excel file I've two sheets, in Sheet1 there is relation with some columns in Sheet2. I create a copy of my Excel file and open it using OpenXML SDK and need to hide some columns in Sheet1. Can anybody guide me that how i can achieve this using OpenXML? Thanks.

Regards,

Clone/Duplicate current slide using open xml memory stream

$
0
0

here i am duplicate slide and write the code on duplicate slide using memory stream,after performing operation and sending to save and sending to blob without using local path..

issue was clone slide layout(template) not getting and ppt get repairing which saveas in local working fine.

i tried 

public static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)

        {
            Slide currentSlide = (Slide)slideTemplate.Slide.CloneNode(true);

            // Create a new slide part in the presentation 
            var newSlidePart = presentationPart.AddNewPart<SlidePart>();
            currentSlide.Save(newSlidePart);
            newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));
            newSlidePart.AddPart(slideTemplate.SlideLayoutPart, slideTemplate.GetIdOfPart(slideTemplate.SlideLayoutPart));

            // Copy the image parts
            foreach (ImagePart ipart in slideTemplate.ImageParts)
            {
                ImagePart newipart = newSlidePart.AddImagePart(ipart.ContentType, slideTemplate.GetIdOfPart(ipart));
                newipart.FeedData(ipart.GetStream());
            }

            // Get the list of slide ids 
            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

            // Figure out where to add the next slide (find max slide) 
            uint maxSlideId = 1;
            SlideId prevSlideId = null;
            foreach (SlideId slideId in slideIdList.ChildElements.OfType<SlideId>())
            {
                var part = presentationPart.GetPartById(slideId.RelationshipId);

                if (part == slideTemplate)
                {
                    prevSlideId = slideId;
                }

                if (slideId.Id > maxSlideId)
                {
                    maxSlideId = slideId.Id;
                }
            }

            maxSlideId++;
            SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
            newSlideId.Id = maxSlideId;
            newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
            return newSlidePart;
        }

Viewing all 1288 articles
Browse latest View live


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