嗨,我已经搜索了这个代码创建一个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 –