簡體   English   中英

如何將CSV文件保存到用戶選擇的位置?

[英]How do i save my CSV file to a location for the user to select?

嗨,我已經搜索了創建csv文件的代碼,但這只能通過指示默認位置來起作用。 如果我想定義文件位置該怎么辦?

    private void btnExport_Click(object sender, EventArgs e)
{
    //Build the CSV file data as a Comma separated string.
    string csv = string.Empty;

    //Add the Header row for CSV file.
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        csv += column.HeaderText + ',';
    }

    //Add new line.
    csv += "\r\n";

    //Adding the Rows
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            //Add the Data rows.
            csv += cell.Value.ToString().Replace(",", ";") + ',';
        }

        //Add new line.
        csv += "\r\n";
    }

    //Exporting to CSV.
    string folderPath = "C:\\CSV\\";
    File.WriteAllText(folderPath + "DataGridViewExport.csv", csv);
}

使用SaveFileDialog

SaveFileDialog dialog = new SaveFileDialog();
DialogResult result = dialog.ShowDialog();
string selectedPath = "";
if (result == DialogResult.OK)
{
    selectedPath = dialog.FileName;
}

您可以選擇諸如開始目錄等選項,但總體而言,它非常易於使用。

暫無
暫無

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

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