首页 > 解决方案 > 文件格式和扩展名不匹配。文件可能已损坏或不安全

问题描述

我正在使用我的代码中DocumentFormat.OpenXml的库创建一个包含多个工作表的 Excel 文件。C#该文件的创建没有任何问题,并且它具有所有必需的数据,但是当我打开它时,我收到此错误弹出窗口:

在此处输入图像描述

我注意到这个错误文件的类型为XSLX file. 如果它是 type Microsoft Excel Worksheet,奇怪的是,它不会抛出任何错误: 在此处输入图像描述

我只是不明白这里出了什么问题以及如何解决它。需要建议,请。下面是我的代码片段:

private static void WriteToExcelFile(HashSet<string> modules, Dictionary<string, HashSet<MyData>> dataDictionary)
        {
            if (!Directory.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Content\\MyDocument")))
                Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Content\\MyDocument"));

            string fileFullname = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Content\\MyDocument", "MyExcel.xslx");
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(fileFullname, SpreadsheetDocumentType.Workbook);

            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); // Add a WorkbookPart to the document
            workbookpart.Workbook = new Workbook();

            // Add Sheets to the Workbook  
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());

           // populate sheets
           .....

           spreadsheetDocument.Close();
}

标签: c#asp.netexcelasp.net-mvcopenxml

解决方案


错误来自错误的扩展名:它必须是 .xlsx 而不是 .xslx


推荐阅读