简体   繁体   中英

C# Problem opening excel file using `OpenXml` from `byte[]`

I have a problem when saving and opening a file with OpenXml library. Here is my code:

    public static void SaveExcel(List<Dictionary<string, object>> listData, List<string> entityTypes, string appName)
    {
        using (var ms = new MemoryStream())
        using (var excel = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
        {
            
            var workBookPart = excel.AddWorkbookPart();
            workBookPart.Workbook = new Workbook();
            var workSheetPart = workBookPart.AddNewPart<WorksheetPart>();
            var workSheetData = new SheetData();
            workSheetPart.Worksheet = new Worksheet(workSheetData);
            var sheets = workBookPart.Workbook.AppendChild(new Sheets());
            var index = 1;
            foreach (var entityType in entityTypes)
            {
                
                var sheet = new Sheet
                {
                    Id = excel.WorkbookPart.GetIdOfPart(workSheetPart),
                    SheetId = 1U,
                    Name = entityType
                };
                sheets.AppendChild(sheet);
            }

            workBookPart.Workbook.Save(ms);
            File.WriteAllBytes("D:/nothing123.xlsx", ms.ToArray());
        }
    }

I am pretty sure I did the right thing though I have this error when opening the file:

Excel cannot be opened the file 'nothing123.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and the file extension matches the format of the file.

Any idea whats going on with my code?

I don't know if this is relevant to the tag but I made up my mind to use ClosedXml library since it's much easier to use than OpenXml . I can easily create a DataTable and create an Excel file out of the DataTable which is very convenient. Here is my quick sample code:

Sample Data Table

public DataTable getData() {    
        DataTable dt = new DataTable();   
        dt.TableName = "SheetName1";  
        dt.Columns.Add("FirstName");  
        dt.Columns.Add("LastName");     
        var row = dt.NewRow();
        row["FirstName"] = "Alvin";
        row["LastName"] = "Quezon"; 
        dt.Rows.Add(row);
        return dt;  
} 

Sample Code to Excel to Byte Array

public static byte[] GetExcelBytes(DataTable dataTable)
    {
        using (var ms = new MemoryStream())
        using (var workBook = new XLWorkbook())
        {
            workBook.Worksheets.Add(dataTable);
            workBook.SaveAs(ms);
            return ms.ToArray();
        }
    }

I didn't get any issue when opening the file and with superb minimal code usage.

Hopefully this will help anyone would like to use this in the future.

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