简体   繁体   English

如何将DateTime.Now中的值写入Excel

[英]How can i write the value from DateTime.Now into Excel

I am working on a school project and im using microsoft visual studio 2010 language c# (I have teached only C and a little bit of C++). 我正在做一个学校项目,我使用的是Microsoft Visual Studio 2010语言C#(我只教过C和一点C ++)。 I am making an Excel file. 我正在制作一个Excel文件。 I'm using something like "add reference", .COM and add library from excel. 我正在使用类似“添加引用”,.COM和从excel添加库的内容。

I can make a page some text in row and col now. 我现在可以在页面的行和列中添加一些文本。

When I push button1_Click , it opens my Excel file, and shows me the string "date" on location [1,2]. 当我按下button1_Click ,它将打开我的Excel文件,并在位置[1,2]上显示字符串"date" For my button2_click he is showing me my DateTime.Now (MessageBox...) 对于我的button2_click他正在向我显示我的DateTime.Now (MessageBox ...)

Short code version: 短代码版本:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //public string ReturnValue1 { get; set; }

        public Form1()
        {
            InitializeComponent();
        }

        public void button1_Click(object sender, EventArgs e)     
        {      
            ....stuff      
            oSheet.Cells[1, 2] = "Date";     
            ....      
            //now i want is oSheet.Cells[2, 2] = .//that shows me the actual date
        }

        public void button2_Click(object sender, EventArgs e)
        {
            DateTime theDate;       //variabele theDate
            theDate = DateTime.Now;  //  Date + time
            MessageBox.Show(theDate.ToString("   dd-MM-yyyy")); //only date
        }
    }
}

Any idea how to deal with it (to send my DATE to print it in Excel) if it is possible? 知道如何处理它(发送我的DATE以便在Excel中打印)吗?

You are pretty much there. 你几乎在那里。 Only thing missing is to set the cell value. 唯一缺少的是设置单元格值。 Try this 尝试这个

public void button2_Click(object sender, EventArgs e)
{
    oSheet.Cells[2, 2] = DateTime.Now.ToString("   dd-MM-yyyy");
}

This will set the date as a string. 这会将日期设置为字符串。 You can also set the data as a date so that Excel can deal with the value directly: 您还可以将数据设置为日期,以便Excel可以直接处理该值:

public void button2_Click(object sender, EventArgs e)
{
    oSheet.Cells[2, 2] = DateTime.Today; // date only, no time
}

Play a little bit around and you'll find how easy it is to set cell and range values. 玩一会儿,您会发现设置单元格和范围值很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM