2017-09-04 46 views
0

嗨,我已經搜索了這個代碼創建一個csv文件,但這隻能通過指示一個默認位置。我應該怎麼做,如果我想定義文件的位置?如何將我的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); 
} 
+4

使用SaveFileDialog – PinBack

+0

旁註:不要在GUI線程上執行此操作...您的應用程序可能在大型數據集上無響應。 – Fildor

+0

參考:https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx –

回答

4

使用SaveFileDialog

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

您可以選擇喜歡的啓動目錄等選項,但總體來說它很容易使用。

+0

嗨如何自定義文件類型和保存文件名稱saveFileDialog? – bob

+1

使用像這樣的過濾器屬性dialog.Filter =「Text Files | * .txt」; –

相關問題