将SQL结果导出为三行文本文件

时间:2018-03-08 22:33:40

标签: c# winforms

以下代码将以下数据从数据库返回到文本文件中。

输出

InvoiceNo  InvoiceDate   Amount   Vat   Total
001          1/1/2018     200     10    210
002          2/1/2018     300     15    315 

我正在寻找的是将Amount,Vat和Total分别与相同的发票信息分开,所以Desired out将如下所示

渴望

   001          1/1/2018     200     
   001          1/1/2018     10
   001          1/1/2018     210
   002          2/1/2018     300
   002          2/1/2018     15
   002          2/1/2018     315

代码

        private void button1_Click(object sender, EventArgs e)
    {
        string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
        string LogFolder = @"C:\Log\";
        try
        {
            string FileNamePart = "Invoice";
            string DestinationFolder = @"C:\Destination\";
            string TableName = "Invoice";
            string FileDelimiter = ","; 
            string FileExtension = ".txt";
            SqlConnection SQLConnection = new SqlConnection();
            SQLConnection.ConnectionString = "Data Source = .\\SQLEXPRESS; Initial Catalog =Backoffice; "
               + "Integrated Security=true;";
            string query = "Select * From " + TableName;
            SqlCommand cmd = new SqlCommand(query, SQLConnection);
            SQLConnection.Open();
            DataTable d_table = new DataTable();
            d_table.Load(cmd.ExecuteReader());
            SQLConnection.Close();
            string FileFullPath = DestinationFolder + "\\" + FileNamePart + "_" + datetime + FileExtension;
            StreamWriter sw = null;
            sw = new StreamWriter(FileFullPath, false);
            int ColumnCount = d_table.Columns.Count;
            for (int ic = 0; ic < ColumnCount; ic++)
            {
                sw.Write(d_table.Columns[ic]);
                if (ic < ColumnCount - 1)
                {
                    sw.Write(FileDelimiter);
                }
            }
            sw.Write(sw.NewLine);
            foreach (DataRow dr in d_table.Rows)
            {
                for (int ir = 0; ir < ColumnCount; ir++)
                {
                    if (!Convert.IsDBNull(dr[ir]))
                    {
                        sw.Write(dr[ir].ToString());
                    }
                    if (ir < ColumnCount - 1)
                    {
                        sw.Write(FileDelimiter);
                    }
                }
                sw.Write(sw.NewLine);
            }

            sw.Close();
            MessageBox.Show("Done..");

        }
        catch (Exception exception)
        {

        }

    }

我如何将遗传金额,增值税和总额归档与谢谢分开。

2 个答案:

答案 0 :(得分:1)

修改

我正在考虑这个答案,我意识到我认为你想在其他地方使用这张发票数据。如果您不需要在其他地方使用数据,则可以使用此代码块。它不会将sql调用返回的数据存储在对象中。

try {
    var invoices = new List<Invoice>();
    using (var SQLConnection = new SqlConnection(ConnectionString)) {
        SQLConnection.Open();
        using (var cmd = new SqlCommand(query, SQLConnection))
        using (var reader = cmd.ExecuteReader()) {
            while (reader.Read()) {
                // Note: You should handle nulls if the sql columns are nullable
                var number = (int)reader["InvoiceNo"];
                var date = (DateTime)reader["InvoiceDate"];
                var amount = (int)reader["Amount"];
                var vat = (int)reader["Vat"];
                var total = (int)reader["Total"];
                var iNumAndDate = $"{number}{FileDelimiter}{date.ToString("M/dd/yyyy")}{FileDelimiter}";

                sw.Write($"{iNumAndDate}{amount}");
                sw.Write($"{iNumAndDate}{vat}");
                sw.Write($"{iNumAndDate}{total}");
                sw.Write(sw.NewLine);
            }
        }
    }
}
catch (Exception exception) {
    // TODO: Handle exceptions
}

<强>原始

首先,我会创建一个课程来存储每个发票,我们将其称为Invoice

class Invoice
{
    public int Number { get; set; }
    public DateTime Date { get; set; }
    public int Amount { get; set; }
    public int Vat { get; set; }
    public int Total { get; set; }
}

然后,只需将dB中的数据存储在List<Invoice>中,然后循环浏览此列表即可写入文件。

try {
    var invoices = new List<Invoice>();
    using (var SQLConnection = new SqlConnection(ConnectionString)) 
    {
        SQLConnection.Open();
        using (var cmd = new SqlCommand(query, SQLConnection))
        using (var reader = cmd.ExecuteReader()) 
        {
            while (reader.Read())
            {
                invoices.Add(new Invoice {
                    // Note: You should handle nulls if the sql columns are nullable
                    Number = (int)reader["InvoiceNo"],
                    Date = (DateTime)reader["InvoiceDate"],
                    Amount = (int)reader["Amount"],
                    Vat = (int)reader["Vat"],
                    Total = (int)reader["Total"]
                });
            }
        }
    }

    using (sw = new StreamWriter(FileFullPath, false)) 
    {
        foreach (var invoice in invoices) 
        {
            var iNumAndDate = $"{invoice.Number}{FileDelimiter}{invoice.Date.ToString("M/dd/yyyy")}{FileDelimiter}";
            sw.Write($"{iNumAndDate}{invoice.Amount}");
            sw.Write($"{iNumAndDate}{invoice.Vat}");
            sw.Write($"{iNumAndDate}{invoice.Total}");
            sw.Write(sw.NewLine);
        }
    }
}
catch (Exception exception) 
{
    // TODO: Handle exceptions
}

答案 1 :(得分:0)

你可以这样做:

foreach (DataRow dr in d_table.Rows)
{
   StringBuilder builder = new StringBuilder();
   for (int ir = 0; ir < 3; ir++)
   {
       if (!Convert.IsDBNull(dr[ir]))
       {
          builder.Append(dr[ir].ToString());
       }
       builder.Append(FileDelimiter);       
   }

   var lineStart = builder.ToString();
   for (int ir = 3; ir < 6; ir++)
   {
       if (!Convert.IsDBNull(dr[ir]))
       {

          sw.Write(lineStart);   
          sw.Write(dr[ir].ToString());
          sw.Write(sw.NewLine);
       }

   }


}