如何把图片插入Excel的一个单元格中

发布网友 发布时间:2022-02-21 20:08

我来回答

1个回答

热心网友 时间:2022-02-21 21:38

需要添加COM组件--Microsoft Excel 11.0 Object Library 的引用。代码的核心在图片的转换和设置excel显示图片的单元格这个方法转换图片,传入一个excel的workbook对象和转换成字符型的image字段。private void ExtractPicture(Excel.Workbook p_Workbook, string p_imageStr){byte[] v_Bytes = Convert.FromBaseString(p_imageStr);if (v_Bytes.Length 0){FileStream v_FileStream = new FileStream(p_Workbook.FullName + ".jpeg", FileMode.CreateNew);BinaryWriter v_BinaryWriter = new BinaryWriter(v_FileStream);// v_BinaryWriter.Write(v_Bytes);for(int i=0;i<v_Bytes.Length;i++){v_BinaryWriter.Write(v_Bytes[i]);}v_BinaryWriter.Close();v_FileStream.Close();}}下面这个方法在Excel中设置图片位置。private void SetPictureToRange(Excel.Workbook p_Workbook, Excel.Worksheet p_Worksheet, string p_strRangeName){Excel.Pictures v_Pictures = (Excel.Pictures)p_Worksheet.Pictures(Type.Missing);Excel.Picture v_Picture = v_Pictures.Insert(p_Workbook.FullName + ".jpeg", Type.Missing);// Excel的get_Range方法可以得到Excel的单元格,可以用来设置图片显示的位置Excel.Range v_Range = p_Worksheet.get_Range(p_strRangeName, Type.Missing);double v_fFactor = 1;//设置图片大小if (v_Picture.Width * (double)v_Range.Height v_Picture.Height * (double)v_Range.Width)v_fFactor = (double)v_Range.Width / (double)v_Picture.Width;elsev_fFactor = (double)v_Range.Height / (double)v_Picture.Height;v_Picture.Left = (double)v_Range.Left + ((double)v_Range.Width - (v_Picture.Width * v_fFactor)) / 2 + 1;v_Picture.Top = (double)v_Range.Top + ((double)v_Range.Height - (v_Picture.Height * v_fFactor)) / 2 + 1;v_Picture.Width = v_Picture.Width * v_fFactor - 0.5d;v_Picture.Height = v_Picture.Height * v_fFactor - 0.5d;}打开一个Excel很简单private bool WorkbookOpen(string p_strWorkBookName){//returns TRUE if the workbook is open

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com