Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm finding it difficult to get to grips with OpenXML.

All I need to do it read the rows and cells into an object[][].

here is what I have:

C#
SpreadsheetDocument doc = SpreadsheetDocument.Open(new MemoryStream(file), false);
List<Product> products = new List<Product>();
foreach (OpenXmlWorksheetSelector sheet in doc.WorkbookPart.WorksheetParts.Select((ws, i) => OpenXmlWorksheetSelector.Create(doc, ws, i)).Where(worksheetSelector))
{
  object[][] cells = //Error
    sheet.Worksheet.Descendants<Row>()
         .Select(r => r.Descendants<Cell>().Select(c => c.InnerText).ToArray())
                        .ToArray();
  var p = Products(columnDetailSelectors, cells);
  if (p != null)
    products.AddRange(p);
}

The error is "The part has been destroyed"

I split out the query and found that sheet.Worksheet.Descendants<row>() throws the error and in fact most properties of 'sheet' are the same >_<

I know the select looks odd, so I'll break that down too:
OpenXmlWorksheetSelector.Create(doc, ws, i) inherits WorksheetPart to make the selection of worksheets to be processed easier:

C#
public class OpenXmlWorksheetSelector : WorksheetPart
{
    public string WorkBookName { get; set; }
    public string Name { get; set; }
    public int Index { get; set; }

    public static OpenXmlWorksheetSelector Create(SpreadsheetDocument doc, WorksheetPart part, int index)
    {
        return new OpenXmlWorksheetSelector
        {
            Index = index,
            Name = doc.WorkbookPart.Workbook.Descendants<Sheet>().ElementAt(index).Name
        };

    }
}



Originally I was using Interop but I had issues when I tried to use is on my web server. The code has evolved from there so I probably have tunnel vision for my approach. I am also using "ExcelDataReader" for older files but I haven't even begun to test that yet.

Any help or advice is much appreciated
Thanks
Andy ^_^
Posted
Comments
Wombaticus 15-Jan-16 12:14pm    
Can't help directly but - and this is probably a cheat for which I'll get right-royally told off, but never mind :) - if your file is an .xlsx, then by changing that extension to .zip you can extract the contents into a number of .xml files. One of these, in a "xl/worksheets" subfolder will be called "sheet1.xml" (let's assume the data you want is in sheet1) and you can then easily extract the data from there via a number of XML-helper methods. :)
Andy Lanng 18-Jan-16 5:20am    
I had forgotten that tip. I'll stick to using OpenXML but I've been looking at the source and it all makes a LOT more sense.

Good tip ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900