簡體   English   中英

在c#中將listview的內容另存為CSV文件

[英]Saving contents of listview as a CSV File in c#

我有一個帶有列表視圖的獨立c#應用程序,它顯示程序讀取的數據。 我將其保存為一個效果很好的excel文件,但是保存時的數據將全部轉儲到列中,我嘗試將其保存為csv文件,但是我無法做到這一點,我希望每個不同的對象都放在單獨的列中請大家注意,這是我的輸出的設計方式,我希望當我打開excel文件時,每個輸出都放在單獨的列中。

   listView1.Items.Add(vis.brand+ "," + (vis.Count) + ","vis.model + "," + Math.Round(vis.sum));

您可以使用示例,選擇C#版本。

它應該正是您想要實現的目標。 這個函數應該可以解決問題:

    private void Button1_Click(object sender, EventArgs e)
    {
        //declare new SaveFileDialog + set it's initial properties
            SaveFileDialog sfd = new SaveFileDialog {
                Title = "Choose file to save to",
                FileName = "example.csv",
                Filter = "CSV (*.csv)|*.csv",
                FilterIndex = 0,
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };

            //show the dialog + display the results in a msgbox unless cancelled

            if (sfd.ShowDialog() == DialogResult.OK) {

                string[] headers = ListView1.Columns
                           .OfType<ColumnHeader>()
                           .Select(header => header.Text.Trim())
                           .ToArray();

                string[][] items = ListView1.Items
                            .OfType<ListViewItem>()
                            .Select(lvi => lvi.SubItems
                                .OfType<ListViewItem.ListViewSubItem>()
                                .Select(si => si.Text).ToArray()).ToArray();

                string table = string.Join(",", headers) + Environment.NewLine;
                foreach (string[] a in items)
                {
                    //a = a_loopVariable;
                    table += string.Join(",", a) + Environment.NewLine;
                }
                table = table.TrimEnd('\r', '\n');
                System.IO.File.WriteAllText(sfd.FileName, table);
            }
    }

@McRonald的答案基本上可以解決這個問題,但是在重要的情況下將失敗。

如果任何字符串中都有逗號或引號,則會使輸出混亂。 例如,如果您有一個具有LastName和FirstName列的CSV,則后綴為“,Jr”的人會拋出逗號:

LastName, FirstName
Smith, John
Baker, Jr, Fred

我開發了一種擴展方法,該方法將任何必要的轉義應用於正在寫入CSV文件單元格的字符串(該代碼可以縮短,但是按照編寫的方式最容易遵循):

static public class CsvExtensions
{
    static public string CsvQuote(this string text)
    {
        if (text == null)
        {
            return string.Empty;
        }

        bool containsQuote = false;
        bool containsComma = false;
        bool containsNewline = false;
        bool containsCR = false;
        int len = text.Length;
        for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
        {
            char ch = text[i];
            if (ch == '"')
            {
                containsQuote = true;
            }
            else if (ch == ',')
            {
                containsComma = true;
            }
            else if (ch == '\r')
            {
                containsCR = true;
            }
            else if (ch == '\n')
            {
                containsNewline = true;
            }
        }

        bool mustQuote = containsComma || containsQuote || containsCR || containsNewline;

        if (containsQuote)
        {
            text = text.Replace("\"", "\"\"");
        }

        if (mustQuote)
        {
            return "\"" + text + "\"";  // Quote the cell and replace embedded quotes with double-quote
        }
        else
        {
            return text;
        }
    }

}

您可以將所有代碼放在自己的類中,然后像這樣使用它(從@McRonald的答案中提取一行代碼):

table += string.Join(",", a) + Environment.NewLine;

table += string.Join(",", a.CsvQuote()) + Environment.NewLine;

暫無
暫無

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

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