首页 > 解决方案 > 将 Datatable 格式化为类似于电子邮件正文表格的字符串

问题描述

我做了一个小的采购申请。用户选择几个订单并点击“发送电子邮件”。使用数据库中的数据为这些特定订单创建电子邮件。

这就是我现在的做法:

string mailbod = "Following are Orders that need your attention: ";  
mailbod=od.mailbody(orderid,mailbod);//Calling the method that sets up the string  

public string mailbody(List<int>oids,string mailbod)
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            string output = "";
            using (SqlConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("TESTDB")))
            {
                StringBuilder sb = new StringBuilder("Select Distinct a.VEND_NAME,b.*  from dbo.Purch_Vendor a inner join dbo.purch_order b on a.VENDOR_ID=b.VENDOR_ID left join dbo.purch_item c on b.ORDER_ID=c.ORDER_ID Where ");
                if (oids.Count > 0)
                {
                    foreach(int x in oids)
                    {
                        sb.Append("b.ORDER_ID" + "=" +  x  + " OR ");
                    }
                    sb.Length--;
                    sb.Length--;
                    sb.Length--;

                    SqlCommand command = new SqlCommand(sb.ToString(), connection);
                    SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
                    DataTable dtRecord = new DataTable();
                    sqlDataAdap.Fill(dtRecord);

                    foreach (DataRow x in dtRecord.Rows)
                    {
                        //' Loop through each column. '
                        for (int i=0;i<dtRecord.Columns.Count; i++)
                        {// ' Output the value of each column's data.

                            sw.Write(x[i].ToString() + ", ");
                        }
                        output = sw.ToString();
                        //' Trim off the trailing ", ", so the output looks correct. '
                        if (output.Length > 2)
                        {
                            output = output.Substring(0, output.Length - 2);
                        }
                        //' Display the row in the console window. '
                        Console.WriteLine(output);
                    }

                    return output;
                }
                else
                {
                    return "";
                }
            }
        }  

通过电子邮件发送的输出如下所示:

亚马逊, 2, 1, 2/20/2020 12:00:00 AM, kjhgg, 34.400, N, awefwef

我想得到的输出:
以下是需要您注意的订单:

只是上述文本的实际表格格式

我怎样才能让它尽可能地工作?任何想法表示赞赏

标签: c#datatablestring-formatting

解决方案


推荐阅读