Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在excel csv文件中添加两个表?_C#_Excel_Csv_Export - Fatal编程技术网

C# 如何在excel csv文件中添加两个表?

C# 如何在excel csv文件中添加两个表?,c#,excel,csv,export,C#,Excel,Csv,Export,我正在使用以下代码创建excel CSV文件。生成第一个图像表对我来说工作正常。但我想生成第二个图像的CSV。有人能告诉我如何在单个文件中添加两个表,如何插入没有列标题的记录,以及如何在excel CSV中添加一个emty行和列吗 CsvExport myExport = new CsvExport(); string fileName = "AbsentEmployeesReport" + Session["id"] + ".csv"; foreach (var item in lstEmpl

我正在使用以下代码创建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());
  }
}

CsvExport myExport=new CsvExport();
string fileName=“缺席员工报告”+会话[“id”]+“.csv”;
foreach(LST员工中的var项目)
{
myExport.AddRow();
myExport[“注册ID”]=item.EnrollNumber;
myExport[“员工(第一名和最后一名)”]=项目名称;
myExport[“部门”]=项目部门;
myExport[“缺席计数”]=item.AbsentCount;
}
字符串myCsv=myExport.Export();
myExport.exportofile(Server.MapPath(“/Reports/”+文件名),myCsv);
使用制度;
使用System.Data.SqlTypes;
使用System.IO;
使用系统文本;
使用System.Collections.Generic;
/// 
///简单CSV导出
公共类CsvExport
{
/// 
///保留列名的有序列表的步骤
/// 
列表字段=新列表();
/// 
///行列表
/// 
列表行=新列表();
/// 
///当前行
/// 
字典currentRow{get{返回行[rows.Count-1];}
/// 
///在此列上设置一个值
/// 
公共对象[字符串字段]
{
设置
{
//跟踪字段名,因为字典会丢失排序
如果(!fields.Contains(field))fields.Add(field);
currentRow[字段]=值;
}
}
/// 
///在设置行上的任何字段之前调用此函数
/// 
public void AddRow()
{
添加(新字典());
}
/// 
///将值转换为它在csv文件中的输出方式
///如果有逗号,则需要用双引号括起来
///例如澳大利亚悉尼->澳大利亚悉尼
///此外,如果它包含任何双引号(“”),则需要将它们替换为四引号[sic](“”)
///例如“危险丹”麦格雷夫->“危险丹”麦格雷夫
/// 
字符串MakeValueCsvFriendly(对象值)
{
如果(value==null)返回“”;
if(value为INullable&((INullable)value).IsNull)返回“”;
if(值为DateTime)
{
如果(((DateTime)值).TimeOfDay.TotalSeconds==0)
返回((日期时间)值).ToString(“yyyy-MM-dd”);
返回((日期时间)值).ToString(“yyyy-MM-dd-HH:MM:ss”);
}
字符串输出=value.ToString();
if(output.Contains(“,”)| output.Contains(“\”)
输出='“'+输出。替换(“\”,“\”)+';
返回输出;
}
/// 
///将所有行作为CSV输出,并返回字符串
/// 
公共字符串导出()
{
StringBuilder sb=新的StringBuilder();
//标题
foreach(字段中的字符串字段)
sb.Append(字段)。Append(“,”);
(某人);
//争吵
foreach(字典行中的行)
{
foreach(字段中的字符串字段)
sb.Append(MakeValueCsvFriendly(行[字段])。Append(“,”);
(某人);
}
使某人返回字符串();
}
/// 
///导出到文件
/// 
公共void导出文件(字符串路径)
{
writealText(路径,Export());
}
/// 
///导出为原始UTF8字节
/// 
公共字节[]导出字节()
{
返回Encoding.UTF8.GetBytes(Export());
}
}
如何生成excel CSV,如下所示:

好吧,CSV代表逗号分隔的值,如果您通过记事本打开生成的文件,您将真正了解这些数据的真实外观,并了解您的要求

  • 要插入空行,只需执行“”、“”、“”
  • 若要插入空列(假设第一列为空),请执行“”“data1”、“data2”
  • 要插入新表2,您的操作与创建表1相同,但首先要在表1之后插入表头。因此,数据应如下所示:
  • 第1-1栏、第1-2栏、第1-3栏
    数据1-1,“数据1-2,数据11-3
    第2-1栏、第2-2栏、第2-3栏
    数据12-1、数据12-2、数据12-3“

    ..…

    首先创建CSV文件的第一部分,然后附加第二部分。空行很简单,就是文件中的一个空行。空单元格可以由相邻的逗号创建。我不清楚传入的数据是什么样子,也不清楚加载的确切方式但是,一般来说,你不需要认为它有标题和数据。只要把它看作行和列。如果你想移动到下一行,请使用
    sb.AppendLine()
    (基本上是添加硬回车)。如果要移动到下一列,只需在StringBuilder中添加逗号,然后再添加下一个单元格的数据。如何理解
    column2-1、column2-2、column2-3
    是第二个表的标题,而不是第一个表的某些数据?