嗨,我已經搜索了這個代碼創建一個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);
}
使用SaveFileDialog – PinBack
旁註:不要在GUI線程上執行此操作...您的應用程序可能在大型數據集上無響應。 – Fildor
參考:https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx –