该文件正在下载一个 xlsx 文件,但是当我尝试打开该文件时,它说文件已损坏。这是我尝试使用的代码,如果需要对以下内容进行任何更改,请告诉我。
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(@"D:\ExcelImport\Input.xml");
xXslt.Load(@"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(@"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
提前致谢
维内特曼格尔