* .CSV文件第一列中的表为空

时间:2019-04-07 12:57:33

标签: c# csv datagridview

我有一个* .csv文件,其中包含一些数据。必须将其打开并用datagridview保存。问题是-保存文件后,我有1列为空。

请参考图片以获取更多详细信息

csv file screenshot

我需要第一列不为空并且将项目计数定义为int。

我需要将“ Item Count”定义为int,否则它将无法正确排序。

using System.Windows.Forms;
using System.IO;

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

         DataTable table = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {

            table.Columns.Add("Item Code", typeof(string)); 
            table.Columns.Add("Item Description", typeof(string));
            table.Columns.Add("Item Count", typeof(int));
            table.Columns.Add("On Order", typeof(string));

            dataGridView1.DataSource = table;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string[] lines = File.ReadAllLines(@"C:\Stockfile\stocklist.csv");
            string[] values;

            for(int i = 1; i < lines.Length; i++)
            {
                values = lines[i].ToString().Split(',');
                string[] row = new string[values.Length];

                for (int j = 0; j < values.Length; j++)
                {
                    row[j] = values[j].Trim(); // split the current line using the separator
                }

                table.Rows.Add(row);

            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV Files (*.csv)|*.csv";
            int count_row = dataGridView1.RowCount;
            int count_cell = dataGridView1.Rows[0].Cells.Count;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(sfd.FileName))
                {
                    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                    {
                        for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
                        {

                            writer.Write("," + dataGridView1.Rows[i].Cells[j].Value.ToString());
                        }
                        writer.WriteLine("");
                    }
                    writer.Close();
                    MessageBox.Show("Done!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

您在每一行的开头都写了一个逗号,因此第1列中有一个空白。

一种解决方案是:

for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
    if (j>0) writer.Write(",");
    writer.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
}