[原创]导出CSV文件,特殊字符处理。

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没有使用
}

转载于:https://www.cnblogs.com/hehexiaoxia/p/4229241.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值