1、將DataTable內容寫入到CSV文件this
/// <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);
}
}string
/// <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 = "";it
//寫出列名稱
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);object
//寫出各行數據
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);
}coding
sw.Close();
fs.Close();
MessageBox.Show("CSV文件保存成功!");
}file
2、將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數據!");
}
}di
/// <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);
}
}while
sr.Close(); fs.Close(); return dt; }