如何以编程方式将xml转换为excel文件

时间:2010-03-22 19:03:46

标签: c# xml

我有一个xml文档,其中包含我的项目的小数据,我想将我的xml转换为excel文件(microsoft office excel 2003及以上版本)

如何以编程方式执行此操作?

8 个答案:

答案 0 :(得分:8)

可以使用Microsoft.Office.Interop.Excel来实现,如下所示:

首先声明这些必要的参考资料。

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using System.Diagnostics;
using Microsoft.Win32;

如图所示创建excel应用程序:

Excel.Application excel2; // Create Excel app
Excel.Workbook DataSource; // Create Workbook
Excel.Worksheet DataSheet; // Create Worksheet
excel2 = new Excel.Application(); // Start an Excel app
DataSource = (Excel.Workbook)excel2.Workbooks.Add(1); // Add a Workbook inside
string tempFolder = System.IO.Path.GetTempPath(); // Get folder 
string FileName = openFileDialog1.FileName.ToString(); // Get xml file name

之后在循环中使用下面的代码来确保复制xml文件中的所有项目

// Open that xml file with excel
DataSource = excel2.Workbooks.Open(FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
// Get items from xml file
DataSheet = DataSource.Worksheets.get_Item(1);
// Create another Excel app as object
Object xl_app;
xl_app = GetObj(1, "Excel.Application");
Excel.Application xlApp = (Excel.Application)xl_app;
// Set previous Excel app (Xml) as ReportPage
Excel.Application ReportPage = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// Copy items from ReportPage(Xml) to current Excel object
Excel.Workbook Copy_To_Excel = ReportPage.ActiveWorkbook;

现在我们有一个名为Copy_To_Excel的Excel对象,其中包含Xml中的所有项目。 我们可以使用我们想要的名称保存和关闭Excel对象。

Copy_To_Excel.Save("thePath\theFileName");
Copy_To_Excel.Close();

答案 1 :(得分:2)

如果您可以控制生成的XML,只需生成XML Spreadsheet文件(Excel 2002和2003的XML文件标准)。

这些在Excel中本机打开,无需更改扩展名。 (要在Excel中默认打开,应将文件扩展名XML设置为使用“XML Editor”打开,“XML Editor”是一个Office应用程序,可根据需要将XML文件路由到Excel,Word,PowerPoint,InfoPath或外部XML编辑器。这是安装Office时的默认映射,但对于某些用户来说可能不合适,特别是在文本编辑器中编辑XML文件的开发人员。)

或者,使用NPOI库生成本机(97/2000 BIFF / XLS)Excel文件而不是XML。

答案 2 :(得分:2)

您甚至可以将XML文件读取为字符串,并使用正则表达式读取标记之间的内容并创建CSV文件或使用xpath表达式读取XML文件数据并导出到CSV文件。

答案 3 :(得分:2)

1.将xml文件填入数据集,
2.通过asp.net中的以下方法将数据集转换为excel

这些是非常简单的方法。

  public static void Convert(System.Data.DataSet ds, System.Web.HttpResponse response)
    {
        //first let's clean up the response.object
        response.Clear();
        response.Charset = "";
        //set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel";
        //create a string writer
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();


        //create an htmltextwriter which uses the stringwriter
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        //instantiate a datagrid
        System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
        //set the datagrid datasource to the dataset passed in
        dg.DataSource = ds.Tables[0];
        //bind the datagrid
        dg.DataBind();


        //tell the datagrid to render itself to our htmltextwriter
        dg.RenderControl(htmlWrite);
        //all that's left is to output the html
        response.Write(stringWrite.ToString());
        response.End();
    }

答案 4 :(得分:1)

我知道没有简单的方法可以从基于xml的电子表格到xls / xlsx进行基于代码的转换。但您可以查看Microsoft Open Xml SDK,它可以让您使用xlsx。您可以构建xlsx电子表格,并将其与您的数据一起提供。在open-xml SDK的层面上,它就像构建xml文件一样。

答案 5 :(得分:0)

对于用','逗号分隔的数组元素,并重复使用相同的列名

1)XML函数

public static class XMLFunctions
{       
    public static List<Tuple<string, string>> GetXMlTagsAndValues(string xml)
    {
        var xmlList = new List<Tuple<string, string>>();

        var doc = XDocument.Parse(xml);

        foreach (var element in doc.Descendants())
        {
            // we don't care about the parent tags
            if (element.Descendants().Count() > 0)
            {
                continue;
            }

            var path = element.AncestorsAndSelf().Select(e => e.Name.LocalName).Reverse();
            var xPath = string.Join("/", path); 

            xmlList.Add(Tuple.Create(xPath, element.Value));
        }

        return xmlList;
    }

    public static System.Data.DataTable CreateDataTableFromXmlFile(string xmlFilePath)
    {
        System.Data.DataTable Dt = new System.Data.DataTable();
        string input = File.ReadAllText(xmlFilePath);

        var xmlTagsAndValues = GetXMlTagsAndValues(input);
        var columnList = new List<string>();

        foreach(var xml in xmlTagsAndValues)
        {
            if(!columnList.Contains(xml.Item1))
            {
                columnList.Add(xml.Item1);
                Dt.Columns.Add(xml.Item1, typeof(string));
            }                    
        }

        DataRow dtrow = Dt.NewRow();
        var columnList2 = new Dictionary<string, string>(); 

        foreach (var xml in xmlTagsAndValues)
        {
            if (!columnList2.Keys.Contains(xml.Item1))
            {
                dtrow[xml.Item1] = xml.Item2;
                columnList2.Add(xml.Item1, xml.Item2);
            }
            else
            {   // Here we are using the same column but appending the next value
                dtrow[xml.Item1] = columnList2[xml.Item1] + "," + xml.Item2;

                columnList2[xml.Item1] = columnList2[xml.Item1] + "," + xml.Item2;
            }

        }

        Dt.Rows.Add(dtrow);

        return Dt;
    }
}

2)完整的Excel课程

using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

public class Excel 
{
    string path = "";
    Application excel = new _Excel.Application();
    Workbook wb;
    Worksheet ws;
    public Range xlRange;

    static bool saveChanges = false;
    static int excelRow = 0;
    static List<string> columnHeaders = new List<string>();    

    public Excel(string path, int Sheet = 1)
    {
        this.path = path;
        wb = excel.Workbooks.Open(path);
        ws = wb.Worksheets[Sheet];
        xlRange = ws.UsedRange;
        excelRow = 0;
        columnHeaders = new List<string>();
    }

    public void SaveFile(bool save = true)
    {
        saveChanges = save;
    }

    public void Close()
    {
        wb.Close(saveChanges);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
        excel.Quit();
    }                      

    public void XMLToExcel(string xmlFilePath)
    {
        var dt = XMLFunctions.CreateDataTableFromXmlFile(xmlFilePath);
        AddDataTableToExcel(dt);
    }

    public void AddDataTableToExcel(System.Data.DataTable table)
    {       
        // Creating Header Column In Excel
        for (int i = 0; i < table.Columns.Count; i++)   
        {
            if (!columnHeaders.Contains(table.Columns[i].ColumnName))
            {
                ws.Cells[1, columnHeaders.Count() + 1] = table.Columns[i].ColumnName;
                columnHeaders.Add(table.Columns[i].ColumnName);
            }
        } 

        // Get the rows
        for (int k = 0; k < table.Columns.Count; k++)
        {
            var columnNumber = columnHeaders.FindIndex(x => x.Equals(table.Columns[k].ColumnName));

            ws.Cells[excelRow + 2, columnNumber + 1] = table.Rows[0].ItemArray[k].ToString();
        }

        excelRow++; 
        SaveFile(true);         
    }
}

3)调用

var excel = new Excel(excelFilename);

foreach (var filePath in files)
{   
    excel.XMLToExcel(filePath); 
}

excel.Close();

对于附加了递增列名(例如column_2)的数组元素

通过XmlFile重做创建数据表

public static System.Data.DataTable CreateDataTableFromXmlFile(string xmlFilePath)
{
    System.Data.DataTable Dt = new System.Data.DataTable();

    string input = File.ReadAllText(xmlFilePath);

    var xmlTagsAndValues = GetXMlTagsAndValues(input);
    var columnList = new List<string>();

    foreach (var xml in xmlTagsAndValues)
    {
        if (!columnList.Contains(xml.Item1))
        {
            columnList.Add(xml.Item1);
            Dt.Columns.Add(xml.Item1, typeof(string));
        }                   
        else 
        {
            var columnName = xml.Item1;

            do
            {
                columnName = columnName.Increment();
            } while (columnList.Contains(columnName));

            columnList.Add(columnName);
            Dt.Columns.Add(columnName, typeof(string));

        }
    }

    DataRow dtrow = Dt.NewRow();
    var columnList2 = new Dictionary<string, string>();  

    foreach (var xml in xmlTagsAndValues)
    {
        if (!columnList2.Keys.Contains(xml.Item1))
        {
            dtrow[xml.Item1] = xml.Item2;
            columnList2.Add(xml.Item1, xml.Item2);
        }
        else
        {
            var columnName = xml.Item1;

            do
            {
                columnName = columnName.Increment();
            } while (columnList2.Keys.Contains(columnName));

            dtrow[columnName] = xml.Item2;
            columnList2[columnName] = xml.Item2;
        }           
    }

    Dt.Rows.Add(dtrow);

    return Dt;
}

字符串扩展

public static class StringExtensions
{
    public static string Increment(this string str)
    {
        if (!str.Contains("_"))
        {
            str += "_2";
            return str;
        }

        var number = int.Parse(str.Substring(str.LastIndexOf('_') + 1));            

        var stringBefore = StringFunctions.GetUntilOrEmpty(str, "_");            

        return $"{stringBefore}_{++number}";
    }
}

使用GetUntilOrEmpty

答案 6 :(得分:-3)

How to open an XML file in Excel 2003

简而言之,您只需使用文件> 打开即可打开它。然后,当您选择XML文件时,系统会提示您选择以下方法之一来导入XML数据:

  • 作为XML列表
  • 作为只读工作簿
  • 使用XML Source任务窗格

答案 7 :(得分:-3)

你不能简单地在Excel中打开它吗?我以为Excel识别后缀XML?