如何将DataTable导出为ex​​cel但保留格式

时间:2017-03-10 04:03:30

标签: c# excel

将DataTable转换为excel时出现了2个问题

  1. 日期格式很混乱,例如我的原始数据是'2016-12-31',在excel中变成'31 -12-16'
  2. Excel删除尾随零,例如'01'变为'1'
  3. 这是代码

    MemoryStream result = new MemoryStream();
    StreamWriter writer = new StreamWriter(result);
    
    CSVwriter csv = new CSVwriter();
    string content = csv.GetFromTable(table);
    writer.Write(content);
    writer.Flush();
    
    return result;
    

    GetFromTable方法

    StringBuilder str = new StringBuilder();
    StringBuilder rowstr = new StringBuilder();
    string Encloser = "\""
    
    foreach (DataRow row in table.Rows) {
        rowstr.Length = 0;
        foreach (DataColumn col in table.Columns) {
            if (col.Ordinal > 0) {
                rowstr.Append(",");
            }
    
            object obj = row(table.Columns.IndexOf(col));
            rowstr.Append(Encloser + ToStr(obj) + Encloser);
        }
        if (rowstr.Length > 0) {
            str.AppendLine(rowstr.ToString());
        }
    }
    
    return str.ToString();
    

    更新:

    str.ToString()结果

    "Date","Code"
    "2016-01-31","01"
    "2016-01-31","02"
    

0 个答案:

没有答案