0

i am making an ajax call to an HttpHandler to save codes, and download excel file with qrcode generated, i need to add the qrcode image in the excel file as below :

string RechargeCardTransaction = "";
if (rechargeDT.Rows.Count > 0)
   RechargeCardTransaction = rechargeDT.Rows[0]["IdRechargeCardTransaction"].ToString();
context.Response.ClearContent();
context.Response.ContentType = "application/download";
context.Response.AddHeader("content-disposition", "attachment;filename=RechargeTransacttionNumnber" + RechargeCardTransaction + ".xls");
context.Response.ContentEncoding = System.Text.Encoding.Unicode;
for (int i = 0; i <= rechargeDT.Rows.Count - 1; i++)
{
   Bitmap qrCodeImage = null;
   Utilities.GenerateBusQRCode(rechargeDT.Rows[i]["RechargeCode"].ToString(), ref qrCodeImage);
   context.Response.Write("RechargeCode\tAmount\tSerialNumber\tQrCode\t");
   context.Response.Write(System.Environment.NewLine);
   context.Response.Write(rechargeDT.Rows[i]["RechargeCode"] + "\t" + Amount 
   + "\t" + rechargeDT.Rows[i]["SerialNumber"].ToString() + "\t" + qrCodeImage + "\t");
}
context.Response.Flush();
context.Response.End();
context.Response.Close();

but i keep getting instead of the bitmap image, a string System.Drawing.Bitmap how can i save the image as it is in the excel file from the handler ashx?

User7291
  • 1,095
  • 3
  • 29
  • 71
  • 1
    The way you're writing to Excel doesn't support adding images. You would need to use a library like EPPlus to create the Excel, and then you can stream that to the response. Here's a [really simple example](https://stackoverflow.com/questions/5738123/using-epplus-with-a-memorystream) of streaming Excel with EPPlus, and here's [inserting an image](https://stackoverflow.com/questions/11588704/adding-images-into-excel-using-epplus). Excel Interop is evil on a good day and Microsoft recommends not using it as part of a web application. – Scott Hannen Apr 10 '19 at 13:11

1 Answers1

0

I am not 100% sure if I understand your code. First, you should separate the two steps of generating the Workbook and sending it to the client.

In your snippet, you are assembling a string. In this case, the ToString() method is used and placed in the string.

The result of qrCodeImage.ToString() is always "System.Drawing.Bitmap"

context.Response.Write(rechargeDT.Rows[i]["RechargeCode"] + "\t" + Amount + "\t" + rechargeDT.Rows[i]["SerialNumber"].ToString() + "\t" + qrCodeImage + "\t");

To solve your problem, you need excel interop. Microsoft.Office.Interop.Excel Namespace