简体   繁体   English

将数据表转换为字节数组

[英]Convert datatable to byte array

I want to convert DataTable to byte array in WCF services. 我想在WCF服务中将DataTable转换为字节数组。 After returning value to presentation layer, I want to convert byte array to excel. 将值返回到表示层后,我想将字节数组转换为excel。 That is to say; 也就是说; I want to do below at presentation layer that is user interface side (web site). 我想在下面的用户界面(网站)的表示层做。

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");

Response.OutputStream.Write(s, 0, s.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
Response.Close();

I didnot do it. 我没做这个。 How can I convert datatable to byte array? 如何将datatable转换为字节数组?

DataTable to Byte [ ] DataTable到字节[]

System.IO.MemoryStream stream = new System.IO.MemoryStream(); 
System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, dtUsers); // dtUsers is a DataTable

byte[] bytes = stream.GetBuffer();

Hope this helps to solve a part of your problems. 希望这有助于解决您的部分问题。

can you try this 你能试试吗

private byte[] ConvertDataSetToByteArray(DataTable dataTable)
    {
        byte[] binaryDataResult = null;
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter brFormatter = new BinaryFormatter();
            dataSet.RemotingFormat = SerializationFormat.Binary;
            brFormatter.Serialize(memStream, dataTable);
            binaryDataResult = memStream.ToArray();
        }
        return binaryDataResult;
    }   

concatenate all columns in your data row and save it as csv (csv is readable in excel) 连接数据行中的所有列并将其保存为csv(csv在excel中可读)

private string (DataTable dt)
{
string rw = "";
StringBuilder builder = new StringBuilder();

foreach(DataRow dr in dt.Rows)
{
  foreach(DataColumn dc in dr.Columns)
  {
      rw = dc[0].ToString();
      if (rw.Contains(",")) rw = "\"" + rw + "\"";
      builder.Append(rw + ",");
  }
  builder.Append(Environment.NewLine);
}
return builder.ToString()
}

Then serialize the return string value 然后序列化返回字符串值

thanks but this return xml when I write the response. 谢谢,但是当我写回复时,这会返回xml。

I'm just thinking from that comment of yours; 我只想从你的评论中思考; If your intention is to benefit from a binding method such as MTOM Encoding etc. by using byte[]; 如果您打算通过使用byte []从MTOM编码等绑定方法中受益; then this is not the way you should transform your data into byte[]. 那么这不是你应该将数据转换为byte []的方式。

[DataContract]
class MyData
{
    [DataMember]
    byte[] binaryBuffer;
    [DataMember]
    string someStringData;
} 

And the configuration for desired bind type such as: 以及所需绑定类型的配置,例如:

<system.serviceModel>
     …
    <bindings>
      <wsHttpBinding>
        <binding name="ExampleBinding" messageEncoding="Mtom"/>
      </wsHttpBinding>
    </bindings>
     …
<system.serviceModel>

You can refer to This Post for more detailed information, there is a very informative dialog about binding types using byte[] and related pages with the code snippets that I gave.. 您可以参考本文了解更多详细信息,有一个非常有用的对话框,关于使用byte []和相关页面的绑定类型以及我给出的代码片段。

Here is the way I did it. 这是我做的方式。 Works great! 效果很好!

        //Get datatable from db 
        DataTable dt = new DataTable();
        dt.TableName = "TABContacts";
        SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
        SqlCommand cmd = new SqlCommand("SELECT * FROM TABContacts", connection);
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            adapter.Fill(dt);
        }

        StringBuilder builder = new StringBuilder();

        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < row.ItemArray.Length; i++)
            {
                string rowText = row.ItemArray[i].ToString();
                if (rowText.Contains(","))
                {
                    rowText = rowText.Replace(",", "/");
                }

                builder.Append(rowText + ",");
            }
            builder.Append(Environment.NewLine);
        }
        //Convert to Byte Array 
        byte[] data = Encoding.ASCII.GetBytes(builder.ToString());

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

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