c# - 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");
}
}
解决方案
推荐阅读
- python - 有没有办法获得可以使用 Azure Python SDK 或 API 在你的 Azure 帐户上创建的最大虚拟机数量?
- java - Android 时间选择器对话框更改首先显示的时间
- excel - 使用 vlookup 函数返回最大值
- amazon-web-services - 如何从 AWS Lambda 函数中扫描 dynamodb 表
- python - pytorch:计算向量函数的向量-雅可比积
- magento - 添加帐单和送货地址以注册表格 Magento 2
- julia - Julia:`import` 和 `using` 的用例
- r - 无法通过 rmarkdown 编织 html
- javascript - 重定向后获取网址
- html - 使用 reactjs 更改主 index.html 上的语言