using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace MatrixCalculator { public static class CsvParser { /// /// Converts a CSV string into a DataTable /// /// CSV /// Separator characters /// Should separators be combined? public static DataTable GetTable(string csv, char[] separators, bool combine = false) { DataTable table = new DataTable("table"); table.Columns.Add(); csv = csv.TrimEnd('\n', '\r'); string[] lines = csv.Split('\n'); for (int i = 0; i < lines.Length; i++) { string[] vals = lines[i].Split(separators, (combine ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None)); table.Rows.Add(""); for (int j = 0; j < vals.Length; j++) { if (j >= table.Columns.Count) table.Columns.Add(); table.Rows[i][j] = vals[j]; } } return table; } /// /// Converts matrix to CSV string /// /// The matrix /// CSV separator character public static string ToCSV (MathNet.Numerics.LinearAlgebra.Matrix m, char sep = ',') { StringBuilder str = new StringBuilder(); for (int i = 0; i < m.RowCount; i++) { for (int j = 0; j < m.ColumnCount; j++) { str.Append(m[i, j]); if (j < m.ColumnCount - 1) str.Append(sep); } str.Append('\n'); } return str.ToString(); } /// /// Converts the data in a DataGridView to CSV format /// /// The DataGridView /// CSV separator public static string ToCSV(System.Windows.Forms.DataGridView m, char sep = ',') { return ToCSV(m, 0, 0, m.Rows.Count, m.Columns.Count, false, sep); } /// /// Converts the data in a DataGridView to CSV format /// /// The DataGridView /// First row in range. /// First column in range. /// Last row in range. /// Last column in range. /// Only selected cells will be taken. /// CSV separator public static string ToCSV(System.Windows.Forms.DataGridView m, int startRow, int startCol, int endRow, int endCol, bool just_selected = false, char sep = ',') { StringBuilder str = new StringBuilder(); for (int i = startRow; i < endRow; i++) { for (int j = startCol; j < endCol; j++) { if (!just_selected || (just_selected && m[j, i].Selected)) str.Append(m[j, i].Value); if (j < m.ColumnCount - 1) str.Append(sep); } str.Append('\n'); } return str.ToString(); } } }