CSV(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号)
CSV文件比较简单,导出表格时格式没有要求的可以导出CSV文件用excel打开
生成CSV文件代码。
namespace CreatCSVFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<int> ii = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
ii.Sort((c1, c2) =>
{
if (c1 == 3)
return 1;
return 0;
});
DataTable dt = new DataTable();
dt.Columns.Add("name", Type.GetType("System.String"));
dt.Columns.Add("sex", Type.GetType("System.String"));
dt.Columns.Add("age", Type.GetType("System.Int32"));
dt.Rows.Add("张三", "男", "22");
dt.Rows.Add("李四", "男", "28");
dt.Rows.Add("王二", "男", "30");
string listSeparator = ";";
string intervalchar = "";
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "保存到CSV文件";
saveFileDialog.Filter = "CSVFile(*.csv)|*.csv";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
if (IsFileUsedByAnotherProcess(path))
{
MessageBox.Show("文件被其他进程占用");
return;
}
if (File.Exists(path))
{
File.Delete(path);
}
using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))//用FileShare.ReadWrite在其他进程占用时也可以读
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine("表格");
DataTableReader dr = dt.CreateDataReader();
while (dr.Read())
{
string str = "";
int len = dr.FieldCount;
int count = 0;
for (int i = 0; i < len; i++)
{
intervalchar = count++ == 0 ? "" : listSeparator;
str += intervalchar + dr.GetValue(i).ToString();
}
sw.WriteLine(str);
}
}
}
}}
private bool IsFileUsedByAnotherProcess(string file)
{
try
{
if (File.Exists(file))
{
using (FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.None))
{
return false;
}
}
return false;
}
catch (Exception ex)
{
return true;
}
}
}
}
要注意的是:分隔符不一定是”,”
系统的列表分隔符是可以在控制面板里设置的,文件内容中的分隔符与系统设置一致时Microsoft Excel才会分隔(系统设置好像对WPS Excel无效,一直都以,为分隔符)
也可以在Excel 数据=》分列 里设置分隔符使其正确显示,不过保存后用txt打开可以发现,这样设置本质是将文件内容里的分隔符给改成了系统设置的分隔符。