【问题标题】:How can i add two tables in excel csv file?如何在 excel csv 文件中添加两个表?
【发布时间】:2015-09-02 19:25:46
【问题描述】:

我正在使用以下代码创建 excel CSV 文件,它对我生成第一个图像表来说工作正常。但我想为第二个图像生成 CSV。谁能告诉我如何在单个文件中添加两个表以及如何在没有列标题的情况下插入记录以及如何在 excel csv 中添加 emty 行和列?

CsvExport myExport = new CsvExport();
string fileName = "AbsentEmployeesReport" + Session["id"] + ".csv";
foreach (var item in lstEmployees)
{
myExport.AddRow();
myExport["Enroll ID"] = item.EnrollNumber;
myExport["Employee (Firt and Last)"] = item.Name;
myExport["Department"] = item.Department;
myExport["Absent Count"] = item.AbsentCount;
}
string myCsv = myExport.Export();
myExport.ExportToFile(Server.MapPath("/Reports/" + fileName), myCsv);

using System;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Collections.Generic;

/// <summary>
/// Simple CSV export
public class CsvExport
{
  /// <summary>
  /// To keep the ordered list of column names
  /// </summary>
  List<string> fields = new List<string>();

  /// <summary>
  /// The list of rows
  /// </summary>
  List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

  /// <summary>
  /// The current row
  /// </summary>
  Dictionary<string, object> currentRow { get { return rows[rows.Count - 1]; } }

  /// <summary>
  /// Set a value on this column
  /// </summary>
  public object this[string field]
  {
    set
    {
      // Keep track of the field names, because the dictionary loses the ordering
      if (!fields.Contains(field)) fields.Add(field);
      currentRow[field] = value;
    }
  }

  /// <summary>
  /// Call this before setting any fields on a row
  /// </summary>
  public void AddRow()
  {
    rows.Add(new Dictionary<string, object>());
  }

  /// <summary>
  /// Converts a value to how it should output in a csv file
  /// If it has a comma, it needs surrounding with double quotes
  /// Eg Sydney, Australia -> "Sydney, Australia"
  /// Also if it contains any double quotes ("), then they need to be replaced with quad quotes[sic] ("")
  /// Eg "Dangerous Dan" McGrew -> """Dangerous Dan"" McGrew"
  /// </summary>
  string MakeValueCsvFriendly(object value)
  {
    if (value == null) return "";
    if (value is INullable && ((INullable)value).IsNull) return "";
    if (value is DateTime)
    {
      if (((DateTime)value).TimeOfDay.TotalSeconds==0)
        return ((DateTime)value).ToString("yyyy-MM-dd");
      return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
    }
    string output = value.ToString();
    if (output.Contains(",") || output.Contains("\""))
      output = '"' + output.Replace("\"", "\"\"") + '"';
    return output;
  }

  /// <summary>
  /// Output all rows as a CSV returning a string
  /// </summary>
  public string Export()
  {
    StringBuilder sb = new StringBuilder();

    // The header
    foreach (string field in fields)
      sb.Append(field).Append(",");
    sb.AppendLine();

    // The rows
    foreach (Dictionary<string, object> row in rows)
    {
      foreach (string field in fields)
        sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
      sb.AppendLine();
    }

    return sb.ToString();
  }

  /// <summary>
  /// Exports to a file
  /// </summary>
  public void ExportToFile(string path)
  {
    File.WriteAllText(path, Export());
  }

  /// <summary>
  /// Exports as raw UTF8 bytes
  /// </summary>
  public byte[] ExportToBytes()
  {
    return Encoding.UTF8.GetBytes(Export());
  }
}

如何生成 excel CSV,如下所示:

【问题讨论】:

  • 首先创建 CSV 文件的第一部分,然后附加第二部分。空行就是这样 - 只是文件中的一个空行。空单元格可以由相邻的逗号创建。
  • 对我来说,您的传入数据是什么样子或您加载它的方式并不明显。但是,一般情况下,您不需要认为它具有标头和数据。只需将其视为行和列。如果要移动到下一行,请使用sb.AppendLine()(基本上添加硬返回)。如果要移动到下一列,只需在 StringBuilder 中添加一个逗号,然后再为下一个单元格添加数据

标签: c# excel csv export


【解决方案1】:

嗯,CSV 代表逗号分隔值,如果您通过记事本打开生成的文件,您将真正看到这些数据的真实样子,并且您会对您的要求有所了解。

  1. 要插入空行,您只需执行 "","","",""
  2. 要插入空列(假设第一列是空的),请执行 "","data1","data2"
  3. 要插入新表 2,您的操作与创建表 1 相同,但首先在表 1 之后插入表头。所以数据应该是这样的:

column1-1,column1-2,column1-3
datat1-1,"data1-2,data11-3
列 2-1、列 2-2、列 2-3
数据12-1,数据12-2,数据12-3"
.....

【讨论】:

  • 怎么可能理解column2-1,column2-2,column2-3是第二个表的表头,而不是第一个表的一些数据?
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
相关资源
最近更新 更多