首页 > 解决方案 > Datagridview 到 CSV 未正确保存

问题描述

我有以下代码将 DataGridView 数据导出到 CSV 文件。然后使用此 CSV 文件将数据导入另一个系统。

但是,当我们导入该文件时,系统并不喜欢它。但是如果我们打开 CSV 文件,点击保存并关闭,系统就会接受它。

当我们手动创建 CSV 时,我们只需将文件保存为“CSV(逗号分隔)”。系统接受的罚款。

我尝试了几种不同类型的 ENCODING,您可以从注释行中看到。

private void SaveToCSV(DataGridView DGV)
        {
            string filename = "";
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV (*.csv)|*.csv";
            sfd.FileName = "DataConversion.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(filename))
                {
                    try
                    {
                        File.Delete(filename);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
                    }
                }
                //Column Names = ""
                string columnNames = "PER_REF_NO,OBJECT,POST_NO,EFFECTIVE_DATE,REP_OBJECT,REP_POST_NO";
                //Count rows in DataGridView + 1
                string[] output = new string[DGV.RowCount + 1];
                output[0] += columnNames;
                int[] cols = new int[] { 0, 1, 11, 18, 21, 22 };

                for (int i = 1; (i - 1) < DGV.RowCount; i++)
                {
                    foreach (int col in cols)
                    {
                        if (col == 1 || col == 21)
                        {
                            output[i] += "POSITION" + ",";
                        }
                        else if (col == 18)
                        {
                            string formatedDate = Convert.ToDateTime(DGV.Rows[i - 1].Cells[col].Value).ToString("yyyMMdd");
                            output[i] += formatedDate + ",";
                        }
                        else
                        {
                            output[i] += DGV.Rows[i - 1].Cells[col].Value?.ToString() + ",";
                        }
                    }
                }
                System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.Default);
                //System.IO.File.WriteAllLines(sfd.FileName, output, Encoding.GetEncoding("Windows-1252"));
                //System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);

                //CLEAR DGV AFTER EXPORT
                DGV.Rows.Clear();
                DGV.Refresh();
                MessageBox.Show("Saved Successfully");
            }
        } 

标签: c#csvformat

解决方案


推荐阅读