需求:将页面dataGridView里的表格存入本地csv文件
本例的dataGridView里的数据由于已经存在DataTable中,故直接出用即可。
1.创建表头
由于DataTable,未将表头存入,故在此进行表头的定义。
public void CreateCSV_Head(string CSV_Head, string fullPath)
{ //定义csv表格的表头
System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Append,
System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
sw.WriteLine(CSV_Head);
sw.Close();
fs.Close();
}
2.保存表格
文件流的System.IO.FileMode.Append属性表示文件读写的追加
public void SaveCSV(DataTable dt, string fullPath)//FTA数据写入csv
{
System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Append,
System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
//定义csv表格的前两个字段
for (int i = 0; i < dt.Rows.Count; i++)
{
string data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
Console.Write(str);
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
}
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
3.实现通过对话框保存
通过Dialog实现保存对话框,并返回文件的全路径,传给SaveCSV方法和CreateCSV_Head方法,实现保存
private void button8_Click_1(object sender, EventArgs e)
{
if (dt.Columns.Count != 6)
{
MessageBox.Show("请完成计算后再进行保存");
}
else
{
//打开保存文件的对话框
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "";
sfd.InitialDirectory = @"C:\";
sfd.Filter = "逗号分隔符| *.csv";
sfd.ShowDialog();
//返回文件全路径
string path = sfd.FileName;
if (path == "")
{
return;
}
string CSV_Head = "字段1,字段2,字段3,字段4,字段5,字段6";//定义表头字段
if (!File.Exists(path))
{
CreateCSV_Head(CSV_Head, path);//如果不存在,创建csv文件,并创建表头
}
try
{//防止csv文件被占用的异常
SaveCSV(dt, path); ;//该算法所有历史结果存储,存在Debug下
}
catch (IOException index0)
{
MessageBox.Show("保存文件出错:" + index0.Message + "请关闭该文件后再执行保存!");
}
}
}
4.总结
此方法可以实现文件保存,但是创建表头和写入其余内容分开写不太合理,待有空改进