一、将DataTable内容写入到CSV文件
/// <summary>
/// 将DataTable中的数据保存成CSV文件
/// </summary>
private void btnSaveCSV_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "CSV文件|*.CSV";
saveFileDialog1.InitialDirectory = "C:\\";
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
else
{
string fileName = saveFileDialog1.FileName;
SaveCSV(ds.Tables[0], fileName);
}
}
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public void SaveCSV(DataTable dt, string fileName)
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string data = "";
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
data += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
MessageBox.Show("CSV文件保存成功!");
}
二、将CSV文件内容读取到DataTable中
/// <summary>
/// 打开CSV并显示其数据
/// </summary>
private void btnOpenCSV_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "CSV文件|*.CSV";
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
else
{
this.dgvShow.DataSource = null;
string fileName = openFileDialog1.FileName;
this.dgvShow.DataSource = OpenCSV(fileName);
MessageBox.Show("成功显示CSV数据!");
}
}
/// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public DataTable OpenCSV(string fileName)
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine=strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
sr.Close();
fs.Close();
return dt;
}