关于MSChart的导出图片功能
MSchart有自带的导出图片功能,但是路径只能写死,不能自由选择路径后再导出,不方便客户使用,经研究几天后,得出了一些结论。
1.SaveFileDialog
一开始在网上搜索后,大多数人都建议SaveFileDialog类中的ShowDialog()可以实现弹出路径选择框,选择路径后将路径传给chart1.SaveImage(localFilePath);
代码如下:
public void ExportChart(Chart chart1, IWin32Window form1)
{
//SystemInformation.UserInteractive = true;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "保存文件";
saveFileDialog.Filter = "JPG文件(*.jpg)|*.jpg|PDF文件(*.pdf)|*.pdf|GIF文件(*.gif)|*.gif|所有文件(*.*)|*.*";
//默认文件类型显示顺序
saveFileDialog.FilterIndex = 2;
//记忆上次保存路径
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog(form1) == DialogResult.OK)
{
if (!string.IsNullOrEmpty(saveFileDialog.FileName))
{
string localFilePath = saveFileDialog.FileName.ToString();
chart1.SaveImage(localFilePath);
}
}
}
在此过程中存在一个问题无法解决,SaveFileDialog只支持Windows.Forms而不支持网页中弹出选择路径框,会报错。所以该思路被毙掉。
2.Response
第二种就是以流的形式导出图片,但是MSChart图片是控件图片,没有以文件的形式保存在本地或服务器上,所以我们先导出一个图片到本地,再提供一个下载的功能,将该图片下载到客户指定的路径处,最后一点,就是删除我们内部指定的路径下的图片,这一点很重要。
代码如下:
/// <summary>
/// MSChart导出图片
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="chart1">空间ID</param>
public void ExportChart(string fileName,Chart chart1)
{
fileName += ".jpg";
string basePath = string.Format("d:\\{0}", fileName);//指定图片生成的路径,用来下载,最后要删除该路径下的图片
chart1.SaveImage(basePath);//导出图片
byte[] bytes = null;
using (FileStream stream = new FileStream(basePath, FileMode.Open))
{
bytes = new byte[(int)stream.Length];
stream.Read(bytes, 0, bytes.Length); //读取流信息
}
//因为我这个函数是写在类中的,所以Response用的是
//System.Web.HttpContext.Current ,如果该函数是写在asp.net页面中的则使用System.Web.UI.Page中的Response
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
File.Delete(basePath); //删除原路径下的图片
}