2009年2月20日 星期五

C# 將 DataGridView 匯出至 CSV 檔案

private void button2_Click(object sender, EventArgs e)
{
string input_date2 = textBox1.Text;
string strValue = string.Empty;
//CSV 匯出的標題 要先塞一樣的格式字串 充當標題
strValue="系統流水號,桃園,機種,條碼,電測工程,日期,時間,其他EQ,樓層,線別,工號,直別,不良項目,不良位置,不良內容,其他1,其他2,其他3,更新時間";
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
{
if (!string.IsNullOrEmpty(dataGridView1[j, i].Value.ToString()))
{
if (j > 0)
strValue = strValue + "," + dataGridView1[j, i].Value.ToString();
else
{
if (string.IsNullOrEmpty(strValue))
strValue = dataGridView1[j, i].Value.ToString();
else
strValue = strValue + Environment.NewLine + dataGridView1[j, i].Value.ToString();
}
}
}

}
//存成檔案(注意!!當有中文字的時候 存檔案一定要用 UTF8)

string strFile = "C:\\FET每日異常紀錄-"+input_date2+".csv";

if (!string.IsNullOrEmpty(strValue))
{
File.WriteAllText(strFile, strValue, Encoding.UTF8);
MessageBox.Show("下載好了");
}

}

}

1 則留言: