I want to export an image to an excel document in c#
The image the following formats:
System.Windows.Media.Imaging.BitmapImage
These are the connection details:
private const string OleDbConnection = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties=Excel 8.0;";
private const string OleDbInsert = "INSERT INTO [Report] ([Time], [Elapsed], [Description], [Picture]) values( @timestamp, @elapsed, @description, @pic);";
private const string OleDbCreate = "CREATE TABLE [Report] ([Time] varchar(255), [Elapsed] varchar(255), [Description] varchar(255), [pic] blob);";
I am using the following code to write the image in excel:
foreach (var e in Entries)
{
using(var command = new OleDbCommand { Connection = connection, CommandText = OleDbInsert })
{
command.Parameters.Add(new OleDbParameter("@component", OleDbType.BSTR) { Value = e.val1 });
command.Parameters.Add(new OleDbParameter("@result", OleDbType.BSTR) { Value = e.val2 });
command.Parameters.Add(new OleDbParameter("@description", OleDbType.BSTR) { Value = e.val3});
if (e.EncodedScreenshot != string.Empty)
{
byte[] imageContent = imageToByteArray(ImageWpfToGDI(e.Picture));
OleDbParameter ph = new OleDbParameter("@pic", OleDbType.Binary) { Value = imageContent};
ph.Size = imageContent.Length;
command.Parameters.Add(ph);
}
}
These are the methods I am using:
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
private System.Drawing.Image ImageWpfToGDI(System.Windows.Media.Imaging.BitmapImage image)
{
MemoryStream ms = new MemoryStream();
var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image as System.Windows.Media.Imaging.BitmapSource));
encoder.Save(ms);
ms.Flush();
return System.Drawing.Image.FromStream(ms);
}
All the data exports to the Excel file except the image (and there definitely exists an image). Could you please give me some advice on how to fix this? I have been searching online alot but I still cannot find a solution.
I made some modifications according to this link: Insert and retrieve Image in Access 2007 DB from C# App. I believe my error is because of the image datatypes. What datatype should I use for the image in the DB and OleDbParameter?
Could someone help me out please? I would be grateful with any response.
Many thanks! :)