c# 创建Excel com加载项图片对象批量操作

时间:2022-04-29 08:26:00

技术含量较低,主要是通过VBA代码转换成c#代码而来,从而实现图片批量插入、删除、另存为的批量操作,增加文档使用的通用性。

插件主要界面如下:

c# 创建Excel com加载项图片对象批量操作

主要代码如下:

   private void button8_Click(object sender, RibbonControlEventArgs e)
{
if (checkBox4.Checked == true)
{
覆盖图片名称插入();
}
else
if (checkBox4.Checked == false)
{
excelapp = Globals.ThisAddIn.Application;
excel.Worksheet wst = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
excel.Range inrow = excelapp.InputBox("选择单元格[行]", Type: );
excel.Range incol = excelapp.InputBox("选择单元格[列]", Type: );
excel.Range oucol = excelapp.InputBox("选择单元格[列]", Type: );
int in_row = inrow.Row;
int in_col = incol.Column;
int ou_col = oucol.Column;
float PicLeft, PicTop, PicWidth, PicHeight;
int n = wst.Cells[incol.Rows.Count, in_col].End().Row;
MessageBox.Show("共:" + n.ToString() + "张图片需要插入");
for (int i = ; i < n + ; i++)
{
if (incol.Columns.Count > || inrow.Rows.Count > || oucol.Columns.Count > )
{
MessageBox.Show("所有的选择:只能为1行或者1列");
break;
}
string str = Convert.ToString(wst.Cells[i, in_col].Value2);
if (str == null || str == string.Empty)
{
continue;
}
wst.Cells[i, ou_col].RowHeight = editBox2.Text;
wst.Cells[i, ou_col].ColumnWidth = editBox1.Text;
string filename = Settings.Default.图片插入文件夹路径 + "\\" + wst.Cells[i, in_col].Value2;
PicLeft = Convert.ToSingle(wst.Cells[i, ou_col].Left);
PicTop = Convert.ToSingle(wst.Cells[i, ou_col].Top);
PicWidth = Convert.ToSingle(wst.Cells[i, ou_col].Width);
PicHeight = Convert.ToSingle(wst.Cells[i, ou_col].Height);
if (checkBox2.Checked == true)
{
wst.Shapes.AddPicture(filename, MsoTriState.msoFalse, MsoTriState.msoTrue, PicLeft, PicTop, -, -);
float r;
foreach (excel.Shape shp in wst.Shapes)
{
if (shp.Type == MsoShapeType.msoPicture)
{
float rh = PicHeight / shp.Height;
float rw = PicWidth / shp.Width;
if (rw > rh)
{
r = rh;
}
else
{
r = rw;
}
//shp.Left = PicL;
//shp.Top = PicT;
shp.ScaleWidth(r, MsoTriState.msoFalse, MsoScaleFrom.msoScaleFromTopLeft);
}
}
}
else
{
wst.Shapes.AddPicture(filename, MsoTriState.msoFalse, MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
}
}
if (checkBox1.Checked == true)
{
跟随单元格();
}
else
{
不随单元格();
}
}
}