打开XML SDK - 保存模板文件(.xltx到.xlsx)

SA.*_*SA. 5 excel openxml openxml-sdk

我有以下代码打开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());    
        }
Run Code Online (Sandbox Code Playgroud)

amu*_*rra 7

为此,您需要使用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()); 
}
Run Code Online (Sandbox Code Playgroud)

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