使用OpenXML将xml数据导出到Excel

时间:2012-07-10 10:20:56

标签: excel openxml export-to-excel xmldatasource

该文件正在下载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;
}

提前致谢

Vineet Mangal

1 个答案:

答案 0 :(得分:0)

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument xmlobj = new XmlDocument();
            xmlobj.Load(@"C:\Excel Import\\Input.xml");
            XslCompiledTransform xXslt = new XslCompiledTransform();
            xXslt.Load(@"C:\ExportToexcel\Data.xslt");

            StringWriter sw = new StringWriter();

            xXslt.Transform(xmlobj, null, sw);
            richTextBox2.Text = sw.ToString();
            sw.Close();
            XmlDocument Xdoc = new XmlDocument();
            Xdoc.LoadXml(sw.ToString());
            Xdoc.Save(@"c:\temp\output.xml");
            StreamReader sr = File.OpenText(@"c:\temp\output.xml");

            string strSheetData = sr.ReadToEnd();
            ArrayList DataNode = new ArrayList();
            ArrayList FinalXML = new ArrayList();
            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 sw1 = new StringWriter();
                xXslt.Transform(xml, null, sw1);
                FinalXML.Add(sw1);
                sw.Close();
                k++;
            }

            using (SpreadsheetDocument doc = SpreadsheetDocument.Create(@"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbook1 = doc.AddWorkbookPart();
                string XML;
                string WorbookXML;
                WorbookXML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
                for (int j = 0; j < DN.Count; j++)
                {
                    WorksheetPart[] sheet = new WorksheetPart[DN.Count];
                    sheet[j] = workbook1.AddNewPart<WorksheetPart>();
                    string sheetId = workbook1.GetIdOfPart(sheet[j]);
                    XML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/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=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\"  r:id=\"" + sheetId.ToString() + "\" />";
                    AddPartXml(sheet[j], text);**
                }
                WorbookXML += "</sheets></workbook>";
                AddPartXml(workbook1, WorbookXML);
                doc.Close();
            }

        }

        public void AddPartXml(OpenXmlPart part, string xml)
        {
            **using (Stream stream = part.GetStream())
            {
                byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
                stream.Write(buffer, 0, buffer.Length);
            }**
        }