簡體   English   中英

在將數據導出到數據庫表時,從 csv 單元格中轉義逗號(,)

[英]Escape comma(,) from a csv cell while while exporting its data to database table

我有一個 csv 文件,其中有一個包含逗號的字段。 例如,在辦公室位置列下,我有一個值 xyz,建築。 當我通過調試器檢查值時,它只顯示“\”xyz”。我已經嘗試使用Replace(",","")Replace("\"","") ,但它失敗了. 此外,我在結果中得到了額外的\ ,如紅色圓圈所示。

我在調試時附上了圖像,顯示了 csv 行的結構。 問題出在紅色圓圈區域。

在此處輸入圖像描述

我也嘗試過關注 function:

public static string RemoveColumnDelimitersInsideValues(string input)
    {

        const char valueDelimiter = '"';
        const char columnDelimiter = ',';

        StringBuilder output = new StringBuilder();

        bool isInsideValue = false;
        for (var i = 0; i < input.Length; i++)
        {
            var currentChar = input[i];

            if (currentChar == valueDelimiter)
            {
                isInsideValue = !isInsideValue;
                output.Append(currentChar);
                continue;
            }

            if (currentChar != columnDelimiter || !isInsideValue)
            {
                output.Append(currentChar);
            }

        }
        return output.ToString();
    }

請幫助解決問題。 謝謝

您看到的 \ 字符不在實際字符串中,它只是在調試器視圖中添加的 escaping 字符。

單擊放大鏡以獲取字符串的實際值。

在此處輸入圖像描述

希望能幫助到你。

String.Replace不會修改現有字符串,它會返回一個新字符串。 因此,您在IsNullOrEmpty檢查之外有相同的舊row字符串。

另外,您說的是,您正在嘗試轉義逗號和引號,但是您正在代碼中將其刪除。

如果要刪除逗號和引號,您的代碼可能如下所示

if (string.IsNullOrEmpty(row))
{
    row = row.Replace(",", "").Replace("\"", "");
}

如果你想轉義引號和逗號,你的代碼可能看起來像

if (row != null && row.Contains(","))
{
    row = "\"" + row.Replace("\"", "\"\"") + "\"";
}

嘗試使用 TextFieldParser,在 csv 中,如果列值有逗號,則列值用 qoutes 進行轉義,因此將 HasFieldsEnclosedInQuotes 添加到 true 將自動將其讀取為單列。

using Microsoft.VisualBasic.FileIO;


using (TextFieldParser reader = new TextFieldParser(csvpath))
       {
         reader.Delimiters = new string[] { "," };
         reader.HasFieldsEnclosedInQuotes = true;
         string[] col =  reader.ReadFields();
       }

您的代碼有 3 個問題值得指出。

1. 解析 CSV 可能會很棘手

你會正確處理多行字符串嗎? 您是否會編寫代碼來處理其中一列中的" (所以轉義" )?

我建議使用 csv 讀取庫(又名 NuGet 包)。

沒有反斜杠

這是一個文件。

1,"The string in the first row has a comma, and an f, in it"
2,The string in the 2nd row does not have a comma in it 

這是 Visual Studio 顯示的內容(我在這里使用 VS Code)。

在此處輸入圖像描述

這是 Console.WriteLine 打印的內容。

1,"The string in the first row has a comma, and an f, in it"
2,The string in the 2nd row does not have a comma in it 

3.替換逗號

即使您處理引號,替換逗號不會擺脫字段分隔符嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM