Search code examples
c#openxml

Openxml - Save non standard xlsx in standard format


I have a tool that can read Xls and Xlsx files via a data reader. I am able to go through the column headers to create a table in Sql server then use the data reader to pump the data into the table.

One of my customer sends xlsx files that can be opened by Excel but does not work with my tool. I am guessing that the xlsx is generated by a third party application and not Excel.

If I open the file in Excel and save it, the file works with the tool. I can even do this in C# using Excel.Application. However I do not want to install Office on my server so this is not an option.

My idea was to use Openxml to open and save the file. While this seems to work it does not 'fix' the format in the way Excel does.

Anybody have experience with Openxml? Maybe you have an idea for me to try?

        using (SpreadsheetDocument ssd = SpreadsheetDocument.Open(FileName, true))
        {
            WorkbookPart wbPart = ssd.WorkbookPart;
            WorksheetPart wsPart = wbPart.WorksheetParts.First();

            wsPart.Worksheet.Save();
            wbPart.Workbook.Save();
        }

Solution

  • Working with ClosedXml:

        private void ReSaveXlsx(string FileName)
        {
            using (XLWorkbook WorkBookNew = new XLWorkbook(FileName))
            {
                WorkBookNew.Worksheets.Delete(1);
                using (XLWorkbook Workbook = new XLWorkbook(FileName))
                {
                    foreach (var Worksheet in Workbook.Worksheets)
                    {
                        WorkBookNew.AddWorksheet(Worksheet);
                    }
                    WorkBookNew.SaveAs(FileName);
                }
            }
    
        }