简体   繁体   中英

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. 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#. I have found various ways of converting CSV files to XMLformat; XSLT, Linq to CSV, RegEx, and the Filehelper library. Maybe there is a technology that I do not know about.

CSV format:

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.

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. 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. We'll use the XDocument class.

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.

You could also pass the results of GetOrdersFromCSV() to a view in MVC to generate some HTML using Razor . 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).

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; }
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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