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


    CSV文件格式

    1、CSV文件默认以英文逗号(,)做为列分隔符,换行符( )作为行分隔符。
    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没有使用
    }

  • 相关阅读:
    CSRF-防御与攻击
    windows 命令
    Integer.parseInt(String str, int i)
    springCloud springmvc 七牛云存储整合百度富文本编辑器
    jsp 文件
    标签的使用
    富文本编辑器
    项目总结 js
    namenode 和 datanode 节点
    Hadoop wordcount
  • 原文地址:https://www.cnblogs.com/hehexiaoxia/p/4229241.html
Copyright © 2020-2023  润新知