CSV文件格式
1、CSV
文件默認以英文逗號(,)做為列分隔符,換行符(\n)作為行分隔符。
2、CSV
默認認為由
""
括起來的內容是一個欄位,這時不管欄位內容里有除
"
之外字符的任何字符都可以按原來形式引用。
3、若字段內容里含有
",
這時只需將
"
替換成兩個雙引號
("")
即可。
CSV
會將字段里的兩個雙引號
""
顯示成一個。
4、應用char(9)表示按照文本形式顯示(實例紅色字體部分)。
應用實例
private void ExportToSCV(GridView gridview, string path)
{
try
{
if (File.Exists(path) && IsFileInUse(path))
{
MessageBox.Show("文件被占用,請先關閉文件!");
return;
}
StringBuilder sb = new StringBuilder();
string strCols = string.Empty;
foreach (GridColumn col in gridview.Columns)
{
if (!col.Visible) continue;
strCols += col.Caption;
strCols += ",";
}
strCols = strCols.Remove(strCols.Length - 1, 1);
sb.AppendLine(strCols);
for (int i = 0; i < gridview.RowCount; i++)
{
string strRow = string.Empty;
foreach (GridColumn col in gridview.Columns)
{
if (!col.Visible) continue;
// 應用char(9)表示按照文本形式顯示
string strValue ="\"" + ((char)(9)).ToString() + gridview.GetRowCellDisplayText(i, col) + "\"";
strRow += strValue;
strRow += ",";
}
strRow = strRow.Remove(strRow.Length - 1, 1);
sb.AppendLine(strRow);
}
using (StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312")))
{
sw.Write(sb.ToString());
sw.Flush();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private bool IsFileInUse(string fileName)
{
bool inUse = true;
FileStream fs = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
inUse = false;
}
catch
{
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;//true表示正在使用,false沒有使用
}