项目需要从数据库读出数据,根据数据绘制条形图和饼图。因为是直接传递一个参数,然后在一个页面显示出全部的图形,而我用datalist绑定图片。以供显示。然后要把这个页面保存成一个excel文件,一开始想直接把最后显示的页面一下保存为excel文件,但是发现不存之后不显示图形。原因是datalist里面绑定图片的语句是这样的
<ItemTemplate>
<IFRAME style="height:400px;width:300px" id="topFrame"name="topFrame" src='Default.aspx?id=<%#DataBinder.Eval(Container.DataItem,"id")%>' frameBorder="no" scrolling="no">
</IFRAME>
</ItemTemplate>
我的这个图片并不是世界存在的,只是请求的时候输出到浏览器里面。所以无法保存。最后想的解决办法是先把图片保存到服务器。然后用excel插件把存放在本地的图片插入到excel文件中去。
第一步:从图像从数据流状态保存为jpg文件
public void save()
{
for (int i = 1; i <= 5; i++)
{
WebRequest request = WebRequest.Create("http://localhost:1629/pic/Default.aspx?id=" + i);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
System.Drawing.Image simg = System.Drawing.Image.FromStream(resStream);
Bitmap newimg = new Bitmap(simg);
int x = newimg.Width - 100;
int y = newimg.Height - 25;
if (y >= 200 && x >= 200)
{
Graphics g = Graphics.FromImage(newimg);
g.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(100, 25), Color.Black, Color.Black), x, y, 100, 25); //Color.FromArgb(0,0,0,0)
g.DrawString("****",new System.Drawing.Font("黑体", 13), new SolidBrush(Color.White), new PointF(x + 4, y + 3));//,FontStyle.Bold
}
newimg.Save(Server.MapPath("execl/") + i + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
resStream.Close();
}
}
然后用excel插件把保存下来的插入到excel文件中
public void insert()
{
Aspose.Excel.License lic = new Aspose.Excel.License();
lic.SetLicense("Aspose.Excel.lic");
ExcelDesigner designer = new ExcelDesigner();
string path = MapPath(".");
//path = path.Substring(0, path.LastIndexOf("//"));
string designerFile = path + "//execl//test.xls";
designer.Open(designerFile);
Cells cells = designer.Excel.Worksheets[0].Cells;
cells[0, 0].PutValue("开发Excel程序");
MemoryStream ss = new MemoryStream();
for (int i = 1; i <= 5; i++)
{
designer.Excel.Worksheets[0].Pictures.Add(3, 3+(i-1)*7, 9, 5+(i-1)*7, path + "//execl//" +i+ ".jpg");
}
designer.Save("test2.xls", SaveType.OpenInExcel, FileFormatType.Default, this.Response);
}
这样就解决了 我的问题了。做个备份。。呵呵。。。