将文本数据导出至Excel有很多种办法,如果是用DevExpress的Grid控件展示数据,那么这个控件本身就提供ExportToExcel的方法,一句话就能搞定。如果是将DataTable或ListModel导出,也有很多组件支持,比如Aspose.Cells、NPIO、微软Office等,网上示例不少,这里不再描述。
今天要分享的,是如何将图片导出至Excel。相当于将采购订单明细导出至Excel,里面要包含商品的图片、规格、数量、金额等。我们用的是Aspose.Cells组件,里面有个Aspose.Cells.Drawing.Picture对象。
完整代码如下
Workbook wb = new Workbook(); Worksheet ws = wb.Worksheets[0]; Cells cell = ws.Cells; //表头样式 Style styHead = wb.Styles[wb.Styles.Add()]; styHead.HorizontalAlignment = TextAlignmentType.Center; //文字居中 styHead.Font.Name = "宋体"; styHead.Font.IsBold = true; //设置粗体 styHead.Font.Size = 12; //设置字体大小 //内容样式 Style numberSty = wb.Styles[wb.Styles.Add()]; numberSty.HorizontalAlignment = TextAlignmentType.Center; numberSty.Font.Size = 10; numberSty.Custom = "0.00"; //内容样式 Style numberSty1 = wb.Styles[wb.Styles.Add()]; numberSty1.HorizontalAlignment = TextAlignmentType.Center; numberSty1.Font.Size = 10; numberSty1.Custom = "0"; //要货明细表头 putValue(cell, "picture", 0, 0, styHead); putValue(cell, "price", 0, 1, styHead); putValue(cell, "qty", 0, 2, styHead); putValue(cell, "amount", 0, 3, styHead); putValue(cell, "goodsCode", 0, 4, styHead); putValue(cell, "seqno", 0, 5, styHead); cell.SetColumnWidth(0, 20); //写入要货明细数据 int row = 1; foreach (var pModel in listDetailModel) { string imageUrl = httpUrl + pModel.ItemImgUrl; var byteImage = FormUIHelper.DownloadData(imageUrl); MemoryStream ms = new MemoryStream(byteImage); int iIndex = ws.Pictures.Add(row, 0, ms); Aspose.Cells.Drawing.Picture pic = ws.Pictures[iIndex]; pic.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating; pic.Height = 130; pic.Width = 100; putValue(cell, pModel.SalePrice, row, 1, numberSty); putValue(cell, pModel.SaleQty, row, 2, numberSty1); putValue(cell, pModel.SaleAmountCn, row, 3, numberSty); putValue(cell, pModel.GoodsCode, row, 4, styHead); putValue(cell, pModel.ChildNo, row, 5, styHead); cell.SetRowHeight(row, 100); row++; } wb.Save(xlsFiName);
代码比较简单,直接看就行了。有不懂的可以留言或加博主微信:xiyang1011
相关阅读
文章评论