Vacate Ответов: 2

Преобразование CSV в datagridview в XML


Эй ребята,

В моем текущем проекте я могу открыть и отобразить CSV-файл в datagridview с возможностью редактирования и сохранения файла.
Я пытаюсь создать кнопку в графическом интерфейсе, которая преобразует отображаемый CSV-файл в формат XML с возможностью сохранения его в нужном формате.

Я очень новичок в этом деле и не совсем уверен, что должен был начать, так что любые подсказки помощи или обратная связь будут очень признательны.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        // Created OpenFileDialog control using a Forms designer at design-time
        {
            openFileDialog1.ShowDialog();
            //called the ShowDialog method to browse a selected file

            txtfilepath.Text = openFileDialog1.FileName;
            BindDataCSV(txtfilepath.Text);
            //set data into textfilepath
        }
        private void BindDataCSV(string filePath)
        {
            string[] lines = System.IO.File.ReadAllLines(filePath);

            DataTable dt = GetDataTable(lines);

            if (dt.Rows.Count > 0)
            {
                dataGridView1.DataSource = dt;
            }
        }

        public DataTable GetDataTable(string[] lines)
        {
            DataTable dt = new DataTable();

            if (lines.Length > 0)
            {
                //first line to create header

                string firstline = lines[0];
                //reads first line of string array at index 0

                string[] headerLabels = firstline.Split(',');
                //splits the firstline using comma delimited string

                foreach (string headerWord in headerLabels)
                {
                    dt.Columns.Add(new DataColumn(headerWord));
                    //added DataColumns for header
                }
             

                //for data


                for (int r = 1; r < lines.Length; r++)
                {
                    string[] dataWords = lines[r].Split(',');
                    //split strings into lines
                    DataRow dr = dt.NewRow();
                    //inset a new row into a data table
                    int columnIndex = 0;
                    //start of column is 0 index
                    foreach (string headerWord in headerLabels)
                    {
                        dr[headerWord] = dataWords[columnIndex++];
                        //increment the value by 1 in columnIndex

                    }
                    dt.Rows.Add(dr);
                    //adds DataRow in the DataTable
                }
            }

            return dt;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // Displays a SaveFileDialog so the user can save the Image            
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "|*.csv";
            saveFileDialog1.Title = "Save CSV File";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
                {
                    WriteDataTable(dataGridView1.DataSource as DataTable, sw, true);
                }


            }
        }

        // Write data to csv

        public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
        {
            if (includeHeaders)
            {
                List<string> headerValues = new List<string>();
                //opened an instance of List<T> for headerValues
                foreach (DataColumn column in sourceTable.Columns)
                {
                    headerValues.Add(QuoteValue(column.ColumnName));
                }

                writer.WriteLine(String.Join(",", headerValues.ToArray()));
            }

            string[] items = null;
            // if string array is null or empty
            foreach (DataRow row in sourceTable.Rows)
            {
                items = row.ItemArray.Select(o => QuoteValue(o.ToString())).ToArray();
                writer.WriteLine(String.Join(",", items));
                // adds rows to the array and joins comma delimited strings
            }

            writer.Flush();
        }

        private static string QuoteValue(string value)
        {
            return String.Concat("\"", value.Replace("\"", "\"\""), "\"");
        }

        private void XML1_Click(object sender, EventArgs e)
        {

        }
    
    }
}


Что я уже пробовал:

Я пробовал другие методы, но не могу понять, как начать с преобразования загруженного файла.

2 Ответов

Рейтинг:
0

Gerry Schmitz

В этом случае XML ничего вам не даст. Экспортируйте его снова в формате CSV. Затем подумайте, что делать с CSV.


Рейтинг:
0