Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have wondering for a way to export and append data-table to existing excel file using C# and OpenXml. I am generating product report sheets and getting problem in Saving that new data. After append a new row successfully, when I read Excel again or Open that particular Excel file I cannot find newly inserted row in file. (means data is not properly written).

If you can provide sample code for this,Its very useful for me.
Thanks In Advance.

What I have tried:

C#
private static void AddRow(SpreadsheetDocument spreadSheetDoc, DataTable table)
        {
            workbookPart = spreadSheetDocument.WorkbookPart;
            IEnumerable<sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<sheets>().Elements<sheet>();
            
            string relationshipId = sheets.Where(s => s.Name == sheetName).SingleOrDefault<sheet>().Id.Value;

            worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
            workSheet = worksheetPart.Worksheet;
            sheetData = workSheet.GetFirstChild<sheetdata>();

            lastRow = sheetData.ChildElements.Count - 1;

            var sheet = workbookPart.Workbook.Descendants<sheet>().FirstOrDefault();

            if (sheet == null)
                throw new Exception("No sheed found in the template file. Please add the sheet");

            int rowIndex = lastRow + 1, colIndex = 0;

            List<string> columns = new List<string>();

            foreach (System.Data.DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);
            }

            foreach (System.Data.DataRow dsrow in table.Rows)
            {
                Row row = new Row();
                foreach (String col in columns)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString());
                    row.AppendChild<cell>(cell);
                }
                sheetData.InsertAt<row>(row, rowIndex);
            }
            workbookPart.Workbook.Save();
        }
Posted
Updated 14-Jul-16 1:26am
v2

1 solution

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