简体   繁体   English

将Excel CSV转换为XML格式Asp.net C#

[英]Convert Excel CSV to XML format Asp.net C#

I am looking for a way to convert my CSV files into XML format and ultimately display the XML in an HTML table. 我正在寻找一种将CSV文件转换为XML格式并最终在HTML表中显示XML的方法。 I have found various ways on doing this on Stack Overflow. 我在堆栈溢出中找到了各种方法来执行此操作。 First, the technologies I'm using are: ASP.NET MVC 4.0 with WCF REST service in C#. 首先,我使用的技术是:具有C#中的WCF REST服务的ASP.NET MVC 4.0。 I have found various ways of converting CSV files to XMLformat; 我发现了将CSV文件转换为XMLformat的各种方法。 XSLT, Linq to CSV, RegEx, and the Filehelper library. XSLT,Linq到CSV,RegEx和Filehelper库。 Maybe there is a technology that I do not know about. 也许有一种我不知道的技术。

CSV format: CSV格式:

ORDER_NUMBER PRODUCT_ID 
12-34-4567 12345 
12-34-4567 12345
12-34-4567 12345 
12-34-4567 12345 
12-34-4567 12345 
12-34-4567 12345

What are your opinions on what approach I should take to do this? 您对我应该采取哪种方法有何看法?

var lines = File.ReadAllLines(@"C:\text.csv");

    var xml = new XElement("TopElement",
       lines.Select(line => new XElement("Item",
          line.Split(';')
              .Select((column, index) => new XElement("Column" + index, column)))));

    xml.Save(@"C:\xmlout.xml"); (from:stackoverflow.com/questions/3069661/convert-csv-file-to-xml?rq=1)

I would first convert from CSV to a native C# object. 我首先要从CSV转换为本地C#对象。

public class Order
{
    public string OrderNumber {get; set;}
    public string ProductId {get; set;}
}

public List<Order> GetOrdersFromCSV(string csv)
{
    //This should be a good place to use FileHelpers, but since the format is so simple we're going to parse it ourselves instead.
    string[] lines = csv.Replace("\r\n","\n").Split('\n'); //Split to individual lines
    List<Order> orders = new List<Order>(); //Create an object to hold the orders
    foreach(string line in lines) //Loop over the lines
    {
        Order order=new Order(); //Create an empty new order object to hold the order
        order.OrderNumber = line.Split(',')[0]; //get first column and put it in the Order as the OrderNumber
        order.ProductId = line.Split(',')[1]; //get second column
        orders.Add(order); //Add the order to the list of orders that we'll return
    }
    return orders;
}

Note that this doesn't handle anything except very simple CSV files, it's usually not a good idea to roll your own parser which is why I suggest existing libraries like FileHelpers. 请注意,除了非常简单的CSV文件外,它不能处理任何其他内容,滚动自己的解析器通常不是一个好主意,这就是为什么我建议使用现有的库(例如FileHelpers)。 Probably a good idea to switch to a more robust system. 切换到更强大的系统可能是个好主意。

Now that you have a list of Order objects, you can turn it into XML. 现在您有了Order对象的列表,可以将其转换为XML。 We'll use the XDocument class. 我们将使用XDocument类。

public static XDocument ConvertToXDocument(IEnumerable<Order> orders) //accept IEnumerable of orders because don't care if it's a list or not as long as we can enumerate over it
{
    XDocument doc =
        new XDocument(
             new XElement("Orders",orders.Select(o =>
                 new XElement("Order",
                      new XAttribute("OrderNo", o.OrderNumber),
                      new XAttribute("ProductId", o.ProductId)))));
    return doc;
}

You can call the .ToString() function on the results of ConvertToXDocument() to get your XML string. 您可以对ConvertToXDocument()的结果调用.ToString()函数以获取XML字符串。

You could also pass the results of GetOrdersFromCSV() to a view in MVC to generate some HTML using Razor . 您还可以将GetOrdersFromCSV()的结果传递到MVC中的视图,以使用Razor生成一些HTML。 Your view might look like this: 您的视图可能如下所示:

@model IEnumberable<Order>

<table>
    <tr>
        <th>Order Number</th>
        <th>Product Id</th>
    </tr>
@foreach(Order order in Orders)
    {
    <tr>
        <td>@order.OrderNumber</td>
        <td>@order.ProductId</td>
    </tr>
    }
</table>

I built a console application that shows it all (except the HTML part). 我构建了一个控制台应用程序,以显示所有内容(HTML部分除外)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication
    {
    public class Class1
        {
        public static string CSVInput = @"12-34-4567,12345 
12-34-4567,12345
12-34-4567,12345 
12-34-4567,12345 
12-34-4567,12345 
12-34-4567,12345";

        public static void Main(string[] args)
            {
            var orders = GetOrdersFromCSV(CSVInput);
            string xml = ConvertToXDocument(orders).ToString();
            Console.WriteLine(xml);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            }

        public static List<Order> GetOrdersFromCSV(string csv)
            {
            //This should be a good place to use FileHelpers, but since the format is so simple we're going to parse it ourselves instead.
            string[] lines = csv.Replace("\r\n", "\n").Split('\n');
            List<Order> orders = new List<Order>();
            foreach (string line in lines)
                {
                Order order = new Order();
                order.OrderNumber = line.Split(',')[0]; //get first column
                order.ProductId = line.Split(',')[1]; //get second column
                orders.Add(order);
                }
            return orders;
            }
        public static XDocument ConvertToXDocument(List<Order> orders)
            {
            XDocument doc =
      new XDocument(
        new XElement("Orders",
            orders.Select(o => new XElement("Order", new XAttribute("OrderNo", o.OrderNumber), new XAttribute("ProductId", o.ProductId)))));
            return doc;
            }
        }
    public class Order
        {
        public string OrderNumber { get; set; }
        public string ProductId { get; set; }
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM