C# .xml 到 .xlsx 如何? [英] C# .xml to .xlsx how?

查看:29
本文介绍了C# .xml 到 .xlsx 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个完整的 XML 文件转换为 XLSX,但我不知道该怎么做.我在 Google 上搜索了一个解决方案,但大多数时候我只能找到另一个方向,例如 XLSX 到 XML.在 Microsoft 页面上,我找到了一个 xmlconvertclass,但我不确定如何使用该类.

I want to convert a complete XML file to XLSX but I'm not sure how I can do it. I searched at Google for a Solutions but the most time I only find the way into the other direction for example XLSX to XML. On the Microsoft Page I found a xmlconvertclass, but I'm not sure how I can work with the class.

过去有人做过类似的事情并且可以帮助我吗?

Did someone do something like this in the past and can help me?

推荐答案

试试下面的代码,我将 XML 转换为 DataSet,然后将 DataSet 导出到 Excel

Try the Below code in which i converted XML into DataSet and later exported DataSet into Excel

        DataSet ds = new DataSet();

        //Convert the XML into Dataset
        ds.ReadXml(@"E:\movie.xml");

        //Retrieve the table fron Dataset
        DataTable dt = ds.Tables[0];

        // Create an Excel object
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

        //Create workbook object
        string str = @"E:\test.xlsx";
        Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(Filename: str);

        //Create worksheet object
        Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;

        // Column Headings
        int iColumn = 0;

        foreach (DataColumn c in dt.Columns)
        {
            iColumn++;
            excel.Cells[1, iColumn] = c.ColumnName;
        }

        // Row Data
        int iRow = worksheet.UsedRange.Rows.Count - 1;

        foreach (DataRow dr in dt.Rows)
        {
            iRow++;

            // Row's Cell Data
            iColumn = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iColumn++;
                excel.Cells[iRow + 1, iColumn] = dr[c.ColumnName];
            }
        }

        ((Microsoft.Office.Interop.Excel._Worksheet)worksheet).Activate();

        //Save the workbook
        workbook.Save();

        //Close the Workbook
        workbook.Close();

        // Finally Quit the Application
        ((Microsoft.Office.Interop.Excel._Application)excel).Quit();

这篇关于C# .xml 到 .xlsx 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆