5

我有以下代码来打开 Excel 模板文件并将其保存为 .xlsx 文件,当我尝试打开新文件时出现以下错误。请帮助解决这个问题。

Excel 无法打开文件“sa123.xlsx”,因为文件格式或扩展名无效。验证文件没有损坏并且文件扩展名与文件格式匹配。

        string templateName = "C:\\temp\\sa123.xltx";
        byte[] docAsArray = File.ReadAllBytes(templateName);
        using (MemoryStream stream = new MemoryStream())
        {
            stream.Write(docAsArray, 0, docAsArray.Length);    // THIS performs doc copy
            File.WriteAllBytes("C:\\temp\\sa123.xlsx", stream.ToArray());    
        }
4

2 回答 2

8

为此,您需要使用Open XML SDK 2.0。以下是我尝试时对我有用的代码片段:

byte[] byteArray = File.ReadAllBytes("C:\\temp\\sa123.xltx");
using (MemoryStream stream = new MemoryStream())
{
    stream.Write(byteArray, 0, (int)byteArray.Length);
    using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
    {
       // Change from template type to workbook type
       spreadsheetDoc.ChangeDocumentType(SpreadsheetDocumentType.Workbook);
    }
    File.WriteAllBytes("C:\\temp\\sa123.xlsx", stream.ToArray()); 
}

这段代码的作用是获取您的模板文件并将其打开到一个SpreadsheetDocument对象中。此对象的类型是Template,但由于您希望它为 a ,因此Workbook您调用ChangeDocumentType方法将其从 a 更改Template为 a Workbook。这将起作用,因为 .xltx 和 .xlsx 文件之间的基础 XML 是相同的,并且它只是导致您出现问题的类型。

于 2010-10-01T02:45:03.553 回答
1

Excel 看到 .xlsx 扩展名并尝试将其作为工作表文件打开。但事实并非如此。这是一个模板文件。当您在 Excel 中打开模板并将其另存为 .xlsx 文件时,它会将其转换为工作表格式。您所做的与更改文件名中的扩展名相同。在 Windows 资源管理器中尝试,您将获得相同的结果。

我相信您应该能够通过使用Excel Object Model来完成您想要的。我还没有使用过这个。

于 2010-09-30T18:09:21.060 回答