【问题标题】:How to insert a single row data in a excel in c#?如何在c#的excel中插入单行数据?
【发布时间】:2017-06-05 12:40:06
【问题描述】:

我有一个方法可以传递四个参数,比如,

public void loggeneration(DateTime datetime, string projectname, int totallines,int sum,int max)
{
}

在上述方法中,我必须创建一个 Excel 工作表(如果文件已经存在,只需将数据附加到最后一个空白行)并连续插入数据(日期时间、项目名称、总和、最大值)五列。

默认情况下,第一行应该是列名。

我已经尽力了,找不到确切的解决方案。有人可以提供解决方案吗?提前致谢

【问题讨论】:

标签: c# .net excel


【解决方案1】:

确实,堆栈溢出中已经存在这个问题。顺便说一下,你可以试试这个简单的解决方案。

  public void loggeneration(DateTime datetime, string projectname, int totallines, int sum, int max)
    {
        // this is the variable to your xls file 
        string path = @"c:\temp\log.xls";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                //once file was created insert the columns
                sw.WriteLine("date;projectname;totallines;sum;max");

            }
        }
        // This text is always added, making the file longer over time
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", datetime, projectname, totallines, sum, max));
        }
    }

【讨论】:

  • 感谢您的回答。整个数据被输入到一个单元格中。您是否有任何想法将数据插入工作表的单独单元格
  • 您好,不客气。对不起我的错误,使用逗号分隔值扩展而不是 xls。替换:字符串路径 = @"c:\temp\log.xls";对于字符串路径 = @"c:\temp\log.csv";祝你好运!
  • 感谢您的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多