1

I want to convert DataTable to byte array in WCF services. After returning value to presentation layer, I want to convert byte array to 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?

2
  • 1
    It's not really clear why you want to convert it to a byte array on the WCF side - all you really care about is getting the DataTable itself to the web site, right? That can convert it to an Excel format. Or did you want to actually do the conversion to Excel at the WCF side, so that the web site can just send the response directly? Commented Dec 11, 2013 at 6:49
  • whilst I agree with what @JonSkeet has said - why do you want to convert a heavy object to byte[] instead of using POCO's or the like? it will also be easily interpreted for non .NET Langs Commented Dec 11, 2013 at 6:51

4 Answers 4

4

DataTable to Byte [ ]

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;
    }   
Sign up to request clarification or add additional context in comments.

1 Comment

thanks but this return xml when I write the response.
0

concatenate all columns in your data row and save it as csv (csv is readable in 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

3 Comments

This might not be the exact answer but it may serve the same purpose.
in rw = dr[0].ToString(); inside the second foreach you mean dc not dr, right?
@Michele, Yes and thank you so much! I've already corrected it.
0

thanks but this return xml when I write the response.

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[]; then this is not the way you should transform your data into 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..

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.