简体   繁体   中英

How to parse multiple sheets in Excel to data-set by using OpenXml

I search lot about how to read and copy data in multiple Excel sheets to data-set using open XML. Only get how to parse single sheet excel to data table. I have a Excel file with multiple sheets. I want to take the data to data-set, so below I pasted the code for copying one sheet data. Please help me to read multiple sheet excel to data-set.

public static DataTable ReadAsDataTable(string fileName)
{

    DataTable dataTable = new DataTable();
    using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
    {
        WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
        IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
        string relationshipId = sheets.First().Id.Value;
        WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
        Worksheet workSheet = worksheetPart.Worksheet;
        SheetData sheetData = workSheet.GetFirstChild<SheetData>();
        IEnumerable<Row> rows = sheetData.Descendants<Row>();

        foreach (Cell cell in rows.ElementAt(0))
        {
            dataTable.Columns.Add(GetCellValue(spreadSheetDocument, cell));
        }

        foreach (Row row in rows)
        {
            DataRow dataRow = dataTable.NewRow();
            for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
            {
                dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
            }

            dataTable.Rows.Add(dataRow);
        }

    }
    dataTable.Rows.RemoveAt(0);

    return dataTable;
}

I understand your requirement clearly and it is very simple to read multiple worksheets in excel using open xml.

you just need to add one for each loop.

I have already create a article with the same requirement in my website,kindly refer that and surely you will get a solution.

http://www.learnandshare-karthik.com/2016/08/29/open-xml-sdk-to-read-workbook-with-multiple-worksheets/

if you still need further help,please let me know

thanks karthik

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM