Hi folks,
right, so the following is a code snippet from someone else who is just using it without bothering how it does what it does. This code is a part of the class that can be used to generate Excel files using C# and NOT using interop. I must say it works, but, i m a bit brain-numbed by the ushort[] arrays and the hex-magic going on. Please have a look and see if you could help me demystify them:
public sealed class ExcelWriter : IDisposable
{
private readonly BinaryWriter writer;
private readonly ushort[] begin = { 0x0809, 8, 0, 0x10, 0, 0 };
private readonly ushort[] end = { 0x0A, 00 };
public ExcelWriter(Stream stream)
{
writer = new BinaryWriter(stream);
}
public void WriteCell(int row, int col, string value)
{
ushort[] data = { 0x0204, 0, 0, 0, 0, 0 };
var len = value.Length;
var plainText = Encoding.ASCII.GetBytes(value);
data[1] = (ushort)(8 + len);
data[2] = (ushort)row;
data[3] = (ushort)col;
data[5] = (ushort)len;
WriteUshortArray(data);
writer.Write(plainText);
}
...
}
I am interested in dissecting the WriteCell() method in particular, which is actually called by a main method, if u will, to write out values from a DataTable using BinaryWriter and FileStream (pretty much standard stuff). I tried something like this which is a heavily stripped down and de-fattened version of this code:
BinaryWriter bw = new BinaryWriter(new FileStream(@"Z:\temp.xls", FileMode.OpenOrCreate));
bw.Write(ASCIIEncoding.ASCII.GetBytes("HELLO\r\n"));
bw.Write(ASCIIEncoding.ASCII.GetBytes("HELLO\r\n"));
bw.Write(ASCIIEncoding.ASCII.GetBytes("HELLO\r\n"));
bw.Flush();
bw.Close();
When I open temp.xls, it opens with a warning about a different format but I can still see my data there. SO I imagine that those little "hexadecimal druids" are doing something mystical that opens the file without any warning.
Please don't point me to "Hexadecimal for Dummies" kinda websites, i know what they are I just want to know what the hell they are doing in an Excel generation code and how? :)
Many thanks...