求助:请大神写个简单的C#方法将一张图片写入excle中!

我喜欢吃包子 2013-06-27 09:55:10
情况时这样我需要向excle模板中写入数据,并打印处理啊。其他的都好做,现在就是需要向某个指定的合并单元格中插入一张图片,不知道怎么写,请个大神写个简单的例子或方法告知小弟一声!
在此,先谢谢咯!

另外请教个问题,在向合并单元格中写入文字时,我想要前面几个字加粗,后面的不加粗,有什么办法么。注意他们是在同一个单元格中。
...全文
89 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
EnForGrass 2013-06-27
  • 打赏
  • 举报
回复
1、用NPOI 操作Excel 添加图片

 strQrCodePath = GetQrCode(p.CardCode);
                    byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath);
                    int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);

                    // Create the drawing patriarch.  This is the top level container for all shapes. 
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();

                    //add a picture
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 2, rowsNum, 2, rowsNum);

                    HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                    pict.Resize();
至于你的第2个问题,我没试过,估计不行
EnForGrass 2013-06-27
  • 打赏
  • 举报
回复

      /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="QrCodeStr">二维码字符串</param>
        /// <returns></returns>
        public string GetQrCode(string QrCodeStr)
        {
            string FileName = imageBasePath + Guid.NewGuid().ToString() + ".png";
            try
            {
                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);
                QrCode qrCode = new QrCode();
                qrEncoder.TryEncode(QrCodeStr, out qrCode);
                GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                using (FileStream stream = new FileStream(FileName, FileMode.Create))
                {
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                }
            }
            catch (Exception ex)
            {
                FileName = "";
                throw ex;
            }
            return FileName;
        }


        protected void btnGenerateCode_Click(object sender, EventArgs e)
        {
            //GenerateQrCodeNet();
            AddPicture();
        }
        /// <summary>
        /// 二维码导出到Excel
        /// </summary>
        protected void AddPicture()
        {
            try
            {
                if (!Directory.Exists(imageBasePath))
                {
                    Directory.CreateDirectory(imageBasePath);
                }
                if (!Directory.Exists(excelBasePath))
                {
                    Directory.CreateDirectory(excelBasePath);
                }
                //创建工作薄
                HSSFWorkbook workbook = new HSSFWorkbook();

                //create sheet
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1");
                string FileName = excelBasePath + DateTime.Now.ToString("yyyyMMddhh24mss") + ".xls";
                //#region 右击文件 属性信息
                //{
                //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                //    dsi.Company = "http://....../";
                //    workbook.DocumentSummaryInformation = dsi;

                //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                //    if (HttpContext.Current.Session["realname"] != null)
                //    {
                //        si.Author = HttpContext.Current.Session["realname"].ToString();
                //    }
                //    else
                //    {
                //        if (HttpContext.Current.Session["username"] != null)
                //        {
                //            si.Author = HttpContext.Current.Session["username"].ToString();
                //        }
                //    }                                       //填加xls文件作者信息     
                //    si.ApplicationName = "NPOI";            //填加xls文件创建程序信息     
                //    si.LastAuthor = "OA系统";           //填加xls文件最后保存者信息     
                //    si.Comments = "OA系统自动创建文件";      //填加xls文件作者信息     
                //    si.Title = "ddd";               //填加xls文件标题信息     
                //    si.Subject = "ddd";              //填加文件主题信息     
                //    si.CreateDateTime = DateTime.Now;
                //    workbook.SummaryInformation = si;
                //}
                //#endregion





                string strQrCodePath = "";
                //填充列标题以及样式
                int rowsNum = 0;  //行号
                HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum);
                HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                headStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.CENTER;
                headerRow.HeightInPoints = 30;

                HSSFFont font = (HSSFFont)workbook.CreateFont();
                font.FontHeightInPoints = 13;
                font.Boldweight = 700;
                headStyle.SetFont(font);

                headerRow.CreateCell(0, CellType.STRING).SetCellValue("卡号");
                headerRow.CreateCell(1, CellType.STRING).SetCellValue("密码");
                headerRow.CreateCell(2, CellType.STRING).SetCellValue("卡二维码");
                //合并列头单元格
                //CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 2, 4);
                //sheet.AddMergedRegion(cellRangeAddress);

                //设置列的宽度
                for (int columnindex = 0; columnindex < 3; columnindex++)
                {
                    headerRow.GetCell(columnindex).CellStyle = headStyle;
                    sheet.SetColumnWidth(columnindex, 5000);
                }

                //填充数据行
                HSSFRow row = null;
                rowsNum = 1;  //行号,从第2行开始
                List<PrintCard> list = (List<PrintCard>)Session["ListPrintCard"];
                foreach (PrintCard p in list)
                {
                    //写入字段值
                    row = (HSSFRow)sheet.CreateRow(rowsNum);
                    HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                    cellStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.CENTER;
                    row.HeightInPoints = 120;
                    HSSFFont cellfont = (HSSFFont)workbook.CreateFont();
                    cellfont.FontHeightInPoints = 10;
                    cellStyle.SetFont(cellfont);

                    row.CreateCell(0, CellType.STRING).SetCellValue(p.CardCode);
                    row.CreateCell(1, CellType.STRING).SetCellValue(p.Password);
                    row.CreateCell(2, CellType.BLANK).SetCellValue("");

                    //合并单元格
                    //CellRangeAddress rowCellRangeAddress = new CellRangeAddress(rowsNum, rowsNum, 2, 4);
                    //sheet.AddMergedRegion(rowCellRangeAddress);

                    strQrCodePath = GetQrCode(p.CardCode);
                    byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath);
                    int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);

                    // Create the drawing patriarch.  This is the top level container for all shapes. 
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();

                    //add a picture
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 2, rowsNum, 2, rowsNum);

                    HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                    pict.Resize();

                    //设置行的高度
                    for (int rowindex = 0; rowindex < 3; rowindex++)
                    {
                        row.GetCell(rowindex).CellStyle = cellStyle;
                    }
                    rowsNum++;
                    //删除图片文件
                    if (File.Exists(strQrCodePath))
                    {
                        File.Delete(strQrCodePath);
                    }
                }
                //供浏览器下载Excel
                if (HttpContext.Current.Request.Browser.Browser == "IE")
                    FileName = HttpUtility.UrlEncode(FileName);
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    HttpContext curContext = HttpContext.Current;

                    // 设置编码和附件格式
                    curContext.Response.ContentType = "application/vnd.ms-excel";
                    curContext.Response.ContentEncoding = Encoding.UTF8;
                    curContext.Response.Charset = "";
                    curContext.Response.AppendHeader("Content-Disposition",
                         "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8));
                    curContext.Response.BinaryWrite(ms.GetBuffer());
                    ms.Close();
                    ms.Dispose();
                    curContext.Response.End();
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "<script>alert('" + ex.Message.ToString() + "');</script>");
            }



        }
我喜欢吃包子 2013-06-27
  • 打赏
  • 举报
回复
引用 1 楼 Chinajiyong 的回复:
1、用NPOI 操作Excel 添加图片

 strQrCodePath = GetQrCode(p.CardCode);
                    byte[] bytes = System.IO.File.ReadAllBytes(strQrCodePath);
                    int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);

                    // Create the drawing patriarch.  This is the top level container for all shapes. 
                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();

                    //add a picture
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 10, 1023, 0, 2, rowsNum, 2, rowsNum);

                    HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                    pict.Resize();
至于你的第2个问题,我没试过,估计不行
新手没学过C# 最近刚自学了一会,能给我说说你的方法么!

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧