I have an excel spreadsheet that I need to be able to import. This spreadsheet has many named tables on it within 1 sheet that have a few different schemas as well as some other random data throughout the sheet. I need to be able to read the data within each individual table.
I have figured out how to get a list of the the tables that are available and how to read their column headers, but I am not sure how I get access to the data.
The following is a sample of the code that I have for reading the headers. I really don't need this information (as I will be putting these into a model and already know the order of the columns), it does show kind of what I am working with.
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 System.Data;
...
public static DataTable GetNamedDataTable(SpreadsheetDocument spreadsheetDocument, string cellRange, string DataTableName)
{
var dataTable = new DataTable();
Workbook woorkbook = spreadsheetDocument.WorkbookPart.Workbook;
//Sheet
var bustedCellRange = BustCellRange(cellRange);
Sheet sheet = woorkbook.Descendants<Sheet>().Where(s => s.Name == bustedCellRange["sheetName"]).FirstOrDefault();
SharedStringTable sharedStringTable = woorkbook.WorkbookPart.SharedStringTablePart.SharedStringTable;
List<SharedStringItem> allSharedStringItems= sharedStringTable.Descendants<SharedStringItem>().ToList();
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);
TableDefinitionPart tableDefinitionPart = worksheetPart.TableDefinitionParts.FirstOrDefault(r => r.Table.Name == DataTableName);
QueryTablePart queryTablePart = tableDefinitionPart.QueryTableParts.FirstOrDefault();
Table excelTable = tableDefinitionPart.Table;
int columnCounter = 0;
foreach(TableColumn column in excelTable.TableColumns)
{
DataColumn dataColumn = dataTable.Columns.Add(column.Name);
dataColumn.SetOrdinal(columnCounter);
columnCounter++;
}
return dataTable;
}