使用ASP.NET MVC将String转换为DataTable

时间:2016-05-20 14:26:49

标签: c# asp.net-mvc datatable

我正在尝试使用ffollowing方法将字符串转换为DataTable,但它确实" nt work

public static DataTable convertStringToDataTable(string data)
    {
        DataTable dataTable = new DataTable();
        bool columnsAdded = false;
        foreach (string row in data.Split('\n'))
        {
            DataRow dataRow = dataTable.NewRow();
            foreach (string cell in row.Split(','))
            {
                string[] keyValue = cell.Split('"');
                if (!columnsAdded)
                {
                    DataColumn dataColumn = new DataColumn(keyValue[0]);
                    dataTable.Columns.Add(dataColumn);
                }
                dataRow[keyValue[0]] = keyValue[1];
            }
            columnsAdded = true;
            dataTable.Rows.Add(dataRow);
        }
        return dataTable;
    }

包含数据字符串的代码:

StringWriter sw = new StringWriter();
                    sw.WriteLine("\"NumClient\",\"Raisons Sociale\",\"DateDocument\",\"NumCommandeNAV\",\"Réference\",\"Designation\",\"QteCommandée\",\"QteLivrée\",\"QteAnnulée\",\"Reste à Livrer\",\"Type Disponibilite\",\"DateDisponibilite\"");

                    var EnTete =
                        db.AURES_GROS_EnTeteCommande.Where(e => e.NumCommandeNAV != " " && e.NumCommandeNAV != "_")
                            .OrderBy(x => x.CodeMagasin)
                            .ThenBy(s => s.NumClient)
                            .ThenBy(c => c.DateDocument)
                            .OrderByDescending(x => x.NumCommandeNAV)
                            .ToList();

                    foreach (var element in EnTete)
                    {
                        string statut = RecuperStatut(element.NumCommandeNAV);
                        if (statut == "A livrer")
                        {
                            Raison = context.Users.First(x => x.No_ == element.NumClient).RaisonSociale;
                            lignes = db.AURES_GROS_LigneCommande.Where(x => x.NumDocument == element.NumDocument).ToList();

                        foreach (var elt in lignes)
                        {
                            sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\"",
                                            element.NumClient,
                                             Raison,
                                             element.DateDocument,
                                             element.NumCommandeNAV,
                                             elt.CodeArticle,
                                             elt.Designation,
                                             elt.Quantite,
                                             0,
                                             elt.QteANNULEE,
                                             elt.Quantite,
                                             element.Couleur,
                                             elt.DateDisponibilite
                                             ));
                            }
                        }
                    }
                    DataTable t = convertStringToDataTable(sw.ToString());

                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.BufferOutput = true;
                    Response.ContentType = "text/excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat" + DateTime.Now.ToString("yyyy_MM_dd") + ".csv");
                    Response.Write(t);
                    Response.Flush();
                    Response.Close();
                    //Response.End();

在此代码中,我希望我将数据导出到Excel文件

任何人都有解决方案 谢谢,

2 个答案:

答案 0 :(得分:2)

我认为你想从字符串创建一个DataTable。首先拆分“行”,然后拆分“列”。您正在行循环中添加DataColumns。在循环之前只需要一次。这是另一个实现,它处理你还没有考虑过的这个和其他边缘情况:

public static DataTable ConvertStringToDataTable(string data)
{
    DataTable dataTable = new DataTable();
    // extract all lines:
    string[] lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
    string header = lines.FirstOrDefault();
    if (header == null)
        return dataTable;
    // first create the columns:
    string[] columns = header.Split(','); // using commas as delimiter is brave ;)
    foreach (string col in columns)
        dataTable.Columns.Add(col.Trim());

    foreach (string line in lines.Skip(1))
    {
        string[] fields = line.Split(',');
        if(fields.Length != dataTable.Columns.Count)
            continue; // should not happen

        DataRow dataRow = dataTable.Rows.Add();
        for (int i = 0; i < fields.Length; i++)
            dataRow.SetField(i, fields[i]);
    }
    return dataTable;
}

答案 1 :(得分:1)

您可以将列foreach转换为for循环。

public static DataTable convertStringToDataTable(string data)
    {
        DataTable dataTable = new DataTable();
        bool columnsAdded = false;
        foreach (string row in data.Split('\n'))
        {
            DataRow dataRow = dataTable.NewRow();
            string[] cell = row.Split(',');
            for (int i = 0; i < cell.Length; i++)
            {
                string[] keyValue = cell[i].Split('"');
                if (!columnsAdded)
                {
                    DataColumn dataColumn = new DataColumn();
                    dataTable.Columns.Add(dataColumn);
                }
                dataRow[i] = keyValue[1];
            }
            columnsAdded = true;
            dataTable.Rows.Add(dataRow);
        }
        return dataTable;
    }

但是如果你的分裂字符串[] keyValue = cell.Split(&#39;&#34;&#39;);没有回复你期望你可能需要进一步调查的东西。