获取控制台应用程序以将数据导出到csv

时间:2014-09-26 15:28:38

标签: c# csv creation

我正在开发一个应用程序,它将从我的sql server获取数据并将其发送到CSV,然后通过电子邮件发送。起初他们只是想要一个控制台应用程序显示我正在填充的数据库,但我从未使用C#来创建csv。任何帮助都会很棒。我的代码看起来像这样。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;

namespace SLA___SQL
{
class Program
{
    static void Main(string[] args)
    {
        sqlExecute();
        string date = System.DateTime.Now.ToString("MMddyyyy");
        Console.WriteLine(date);

    }
    public static void sqlExecute()
    {
        try
        {
            string queryString = "SELECT  [DateReceived],[DateScanned],[AttachmentFileUniqueID],[ApplicationType],[State],[Zip],[NumPages]" +
            ",[DeliveryTime],[Source] FROM [Reports].[dbo].[AppReport] where convert(date, DeliveryTime) = convert(date, GETDATE()-1)";
            string connectionString = "Data Source=Kxx-xxx-xxxx\\KOFAX;" + "Initial Catalog=Reports;" + "User ID=xx;" + "Password=xxxxxxxxxx;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = queryString;
                connection.Open();
                using (SqlDataReader oReader = command.ExecuteReader())
                {
                    while (oReader.Read())
                    {
                        Console.WriteLine(String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}",
                                       oReader["DateReceived"], oReader["DateScanned"], oReader["AttachmentFileUniqueID"], oReader["State"], oReader["Zip"],
                                     oReader["NumPages"], oReader["DeliveryTime"], oReader["Source"]));

                    }


                    connection.Close();
                }
            }
        }

        catch (SqlException ex)
        {
            Console.WriteLine(ex.Message);
            throw new Exception("Error: " + ex.Message);
        }
    }

    public static void emailSend()
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");
        mail.From = new MailAddress("xxx.xxxr@Novitex.com");
        mail.To.Add("xxx.xxx@Novitex.com");
        mail.Subject = "Test Mail - 2";
        mail.Body = "mail with attachment";

        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment("C:\\Users\\xxx1\\Desktop\\test001.pdf");
        mail.Attachments.Add(attachment);

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("xxx.xxx@Novitex.com", "abc@1234");
        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
    }
}

0 个答案:

没有答案