@manhng

Welcome to my blog!

OpenXML + ASP.NET Core WEB API

August 22, 2021 22:10

OpenXml + ASP.NET Core WEB API (edit)

Read and Write Excel using open xml in c# (github.com)

Read the contents of a spreadsheet with C# and OpenXml. - blakepell.com

c# - open xml excel read cell value - Stack Overflow

openxml - From Excel to DataTable in C# with Open XML - Stack Overflow

c# - "Incorrect Content-Type: " exception throws angular mvc 6 application - Stack Overflow

Code Sample

    public class UserDto
    {
        public string Name { getset; }
        public string Email { getset; }
        public string Phone { getset; }
    }
    public class ExportDataService : IExportDataService
    {
        public byte[] ExportListUserDtosToExcel(List<UserDto> users)
        {
            // Lets converts our object data to Datatable for a simplified logic.
            // Datatable is most easy way to deal with complex datatypes for easy reading and formatting.
            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(users), typeof(DataTable));
 
            using (MemoryStream stream = new MemoryStream())
            {
                SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
 
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();
 
                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new SheetData();
                worksheetPart.Worksheet = new Worksheet(sheetData);
 
                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
 
                sheets.Append(sheet);
 
                Row headerRow = new Row();
 
                List<stringcolumns = new List<string>();
                foreach (DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);
 
                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }
 
                sheetData.AppendChild(headerRow);
 
                foreach (DataRow row in table.Rows)
                {
                    Row newRow = new Row();
                    foreach (string col in columns)
                    {
                        Cell cell = new Cell();
                        cell.DataType = CellValues.String;
                        cell.CellValue = new CellValue(row[col].ToString());
                        newRow.AppendChild(cell);
                    }
 
                    sheetData.AppendChild(newRow);
                }
 
                workbookPart.Workbook.Save();
 
                document.Close();
 
                return stream.ToArray();
            }
        }
 
        public async Task<List<UserDto>> GetListUserDtos(IFormFile fileUpload)
        {
            try
            {
                var users = new List<UserDto>();
                string str = string.Empty;
                string sheetName = string.Empty;
                int sheetIndex = 0;
                int colIndex = 0;
                int rowIndex = 0;
 
                using (var stream = new MemoryStream())
                {
                    await fileUpload.CopyToAsync(stream);
 
                    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, false);
 
                    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
 
                    SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
 
                    SharedStringTable sst = sstpart.SharedStringTable;
 
                    foreach (WorksheetPart worksheetpart in workbookPart.WorksheetParts)
                    {
                        try
                        {
                            Worksheet worksheet = worksheetpart.Worksheet;
 
                            sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(sheetIndex++).Name;
 
                            foreach (SheetData sheetData in worksheet.Elements<SheetData>())
                            {
                                try
                                {
                                    var cells = sheetData.Descendants<Cell>();
                                    var rows = sheetData.Descendants<Row>();
 
                                    Debug.WriteLine("Row count  = {0}", rows.LongCount());
                                    Debug.WriteLine("Cell count = {0}", cells.LongCount());
 
                                    string email = string.Empty;
                                    string name = string.Empty;
                                    string phone = string.Empty;
 
                                    foreach (Cell cell in cells)
                                    {
                                        rowIndex += 1;
                                        colIndex += 1;
 
                                        if (colIndex == 1)
                                        {
                                            //Reset value
                                            email = string.Empty;
                                            name = string.Empty;
                                            phone = string.Empty;
                                        }
 
                                        if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
                                        {
                                            int ssid = int.Parse(cell.CellValue.Text);
                                            str = sst.ChildElements[ssid].InnerText;
                                        }
                                        else if (cell.CellValue != null)
                                        {
                                            str = cell.CellValue.Text;
                                        }
 
                                        if (rowIndex > 3 && colIndex % 3 == 1)
                                        {
                                            email = str;
                                        }
                                        if (rowIndex > 3 && colIndex % 3 == 2)
                                        {
                                            name = str;
                                        }
                                        if (rowIndex > 3 && colIndex % 3 == 0)
                                        {
                                            phone = str;
 
                                            //Reset colIndex
                                            colIndex = 0;
 
                                            //Add to list
                                            users.Add(new UserDto()
                                            {
                                                Email = email,
                                                Name = name,
                                                Phone = phone
                                            });
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine(e.ToString());
                                    throw;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.ToString());
                            throw;
                        }
                    }
                }
 
                return users;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                throw;
            }
        }
    }
}

Categories

Recent posts