代码之家  ›  专栏  ›  技术社区  ›  John Wooten

如何将csv文件作为json数据加载到mvc web应用程序中。标题可以不同

  •  0
  • John Wooten  · 技术社区  · 7 年前

    我正在尝试读取csv文件,以便加载jquery数据表。csv文件可能有不同的头。我使用头为jquery表创建列。然后加载文件并创建行。我是从csv文件直接做的,一切正常,但前提是文件很小。我需要使用json来实现一种使用linq对代码的模型部分进行排序、筛选和查询的方法。在尝试转移到mvc模型时,我遇到了一个无法从json数据中提取行的位置。

    这是viewfile,它当前有loaddataasjson(我敢打赌,它应该在model类中)。它创建的json是正确的。

       public IActionResult ViewFile()
        {
            string fileName = Request.Form["fileName"];
            ViewData["name"] = fileName;
            ViewData["data"] = LoadDataAsJson(dir + Path.DirectorySeparatorChar + fileName, 100);
            return View();
        }
    
        private string LoadDataAsJson(string fileName, int limit)
        {
            string[] headers = new string[8];
            StringBuilder bldr = new StringBuilder();
            bldr.Append("[");
            using (TextReader reader = new StreamReader(fileName))
            {
                String line = null;
                int k = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    if (k > limit)
                        break;
                    if (k++ != 0)
                    {
                        if (k != 2)
                            bldr.Append(","); // append a comma to the end of previous line
                        List<string> aRow = FormatAsJsonArray(line);
                        bldr.AppendLine();
                        bldr.Append("{");
                        for (int i = 0; i < headers.Length; i++)
                        {
                            bldr.Append(headers[i]);
                            bldr.Append(":\"");
                            bldr.Append(aRow[i]);
                            bldr.Append("\"");
                            if (i != headers.Length - 1)
                                bldr.Append(",");
                        }
                        bldr.Append("}");
                    }
                    else
                    {
                        headers = line.Split(',');
                    }
                }
            }
            bldr.Append(Environment.NewLine + "]" + Environment.NewLine);
            return bldr.ToString();
        }
    
        private List<string> FormatAsJsonArray(string aLine)
        {
            int k = 0;
            string[] tokens = aLine.Split(',');
            List<string> items = new List<string>();
            string lastPart = "";
            if (tokens.Length > 6)
            {
                for (int i = 7; i < tokens.Length; i++)
                {
                    lastPart = String.Concat(lastPart, tokens[i]);
                    if (i != tokens.Length - 1)
                        lastPart += ",";
    
                }
            }
    
            for (int i = 0; i < tokens.Length; i++)
            {
                if (i > 8)
                    break;
                if (tokens[i].Contains("["))
                {
                    List<string> msecs = MsecColumnAsJson(tokens[i]);
                    for (int kk = 0; kk < msecs.Count; kk++)
                        items.Add(msecs[kk]);
                }
                else if (k < 7)
                    items.Add(tokens[i]);
                k++;
            }
            if (lastPart != null && lastPart.Length > 0)
                items.Add(lastPart);
    
            return items;
        }
    

    viewfile.cshtml部分包含。

    <h2>@ViewData["name"]</h2>
    <div class="container">
        <br />
        <table id="table_id" class="table table-condensed table-striped table-hover display">
            <thead>
                <tr>
                    <th>DateTime</th>
                    <th>Msecs</th>
                    <th>Thread</th>
                    <th>Level</th>
                    <th>Logger</th>
                    <th>Host</th>
                    <th>Msg Type</th>
                    <th>Message</th>
                </tr>
            </thead>
            <tbody>
                @{
                string logFile = (string)@ViewData["data"];
                var k = 0;
                }
                @foreach (string lf logFile)
                {
                if (k++ > 50)
                {
                break;
                }
                <tr>
                    @foreach (string item in lf)
                    {
                    <td>
                        @item
                    </td>
                    }
                </tr>
                }
            </tbody>
        </table>
    </div>
    

    最后,在每个foreach语句中,都无法将类型“char”转换为“string”。我尝试在var logfile=@viewdata[“data”]行中使用var,但是其他的都不起作用。

    我的目的是一次提取json数组行,然后将每一行分解为一个td。如何使用logfilemodel来包含数据的处理,并创建一个视图和控制器来执行此操作?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Miq    7 年前

    我建议换一种方式。

    使用 TextFieldParser Microsoft.VisualBasic.FileIO (是的,您可以在c)中使用它来读取csv并将其作为数据模型放置,然后使用 Newtonsoft.Json 从那个对象创建json。

    以下是有关textfieldparser的更多信息: https://coding.abel.nu/2012/06/built-in-net-csv-parser/