【问题标题】:how to remove the extra commas in numbers in csv file after converting from excel从excel转换后如何删除csv文件中数字中的多余逗号
【发布时间】:2014-11-05 23:07:17
【问题描述】:

我有一个将 excel 文件转换为 csv 文件的代码:

Microsoft.Office.Interop.Excel.Application reportExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks reportBooks = null;
Microsoft.Office.Interop.Excel.Workbook reportBook = null;
Microsoft.Office.Interop.Excel.Sheets reportSheets = null;
Microsoft.Office.Interop.Excel._Worksheet reportSheet = null;
try
{
    reportBooks = reportExcel.Workbooks;
    reportBook = reportBooks.Open(excelFilePath);
    reportSheets = reportBook.Sheets;
    reportSheet = reportSheets.get_Item(1);
    if (File.Exists(csvtempFile))
    {
        File.Delete(csvtempFile);
    }
    reportBook.SaveAs(csvtempFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, false, false);
    ...
}
catch (Exception ex)
{
    ...
}
finally
{
    ...
}

我在 csv 文件中得到下一个文本:

...
"Some strings","309,145","4,964,398",,"1,194,780",,
...

如您所见,数字包含一个额外的逗号。请告诉我如何删除多余的逗号以获得​​下一个值:

"Some strings","309,145","4964,398",,"1194,780",,

【问题讨论】:

  • 你的意思是你想要,"309145","4964398",,"1194780",,
  • 哪个多余的逗号?表示千的,还是表示空列的?
  • 我写道:“如您所见,数字包含一个额外的逗号”,因此:表示千位的数字。
  • 这是您应该尝试实现自己的 CSV 解析器的原因。虽然格式看似简单,但它有很多极端情况和例外情况,就像您刚刚发现的那样。有很多库,如果你稍微搜索一下,它们可以很好地处理这些情况。 CSV 文件还有另一个问题:没有元数据。除非对每个字段的含义有正式的规范,否则您可以知道字段中的数据类型。
  • 所以我给你的建议是:不要制作自己的解析器,并为包含的数据使用可以处理其格式的转换器(例如以逗号作为千位分隔符的数字)。

标签: c# excel csv


【解决方案1】:

查看这篇文章:Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c#

您可以检查列类型,为每个要更改的列设置一个范围,然后在导出之前设置数字格式。

我知道它不漂亮,但如果你找不到更漂亮的东西,它可能会起作用。

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2020-02-20
    • 2023-03-05
    相关资源
    最近更新 更多