Как экспортировать диаграмму MSchart в Excel?
Я создал диаграмму с помощью Mschart. Я хочу экспортировать созданную диаграмму в Excel. Я использую следующий код, но когда я открываю его в Excel, я просто вижу какой-то неизвестный код вместо диаграммы.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
3 ответа
Я обнаружил ту же проблему, и после нескольких попыток я смог найти правильный путь. Это сработало для меня, и код выглядит следующим образом.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = @"<Table><tr><td><img src='" + imgPath2 + @"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Надеюсь это поможет.
Добавьте этот код для вашей глобализации, это работает для меня.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8
Я также сталкивался с таким сценарием в одном из моих проектов.
Вот решение.