我的这个是excel的插件程序,建的是vs.net 2003中的Addin工程,同时适用 vsto程序。
需要添加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.FromBase64String(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);
for ( int i = 0 ;i < v_Bytes.Length;i ++ )
{
v_BinaryWriter.Write(v_Bytes[i]);
}
v_BinaryWriter.Close();
v_FileStream.Close();
}
}
{
byte [] v_Bytes = Convert.FromBase64String(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);
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;
else
v_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.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;
else
v_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 ;
}