问题描述
我有以下代码打开Excel模板文件并保存为.xlsx文件,当我尝试打开新文件时,我会收到以下错误。请帮助解决这个问题。
I have the following code to open Excel template file and save it as .xlsx file and I get the error below when I try to open the new file. Please help to resolve this.
由于文件格式或扩展名无效,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());
}
推荐答案
为了做到这一点将需要使用。以下是我尝试过的代码片段:
In order to do this you will need to use the Open XML SDK 2.0. Below is a snippet of code that worked for me when I tried it:
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());
}
这段代码是做什么的,它需要你的模板文件, a href =http://msdn.microsoft.com/en-us/library/documentformat.openxml.packaging.spreadsheetdocument.aspx =noreferrer> SpreadsheetDocument
对象。该对象的类型是 Template
,但是由于您希望将其作为工作簿
,您可以调用 ChangeDocumentType
方法将其从模板
更改为工作簿
。这将工作,因为基础XML在.xltx和.xlsx文件之间是相同的,它只是导致您出现问题的类型。
What this code does is it takes your template file and opens it into a SpreadsheetDocument
object. The type of this object is Template
, but since you want it as a Workbook
you call the ChangeDocumentType
method to change it from a Template
to a Workbook
. This will work since the underlying XML is the same between a .xltx and a .xlsx file and it was just the type that was causing you an issue.
这篇关于打开XML SDK - 保存模板文件(.xltx为.xlsx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!