我在excel单元格中插入图像,但通常该图像的高度和宽度都比原始单元格大。因此,在插入图像后,我想:根据图像的大小调整特定的Excel行和列的大小。这就是我所拥有的:
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Worksheet ws;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Open(@".../MyExcelFile.xlsx");
ws = wb.Sheets[1];
string picPath = @"..../MyPic.png";
System.Drawing.Image img = System.Drawing.Image.FromFile(picPath);
var size = img.Size;
Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 5];
float Left = (float)((double)oRange.Left);
float Top = (float)((double)oRange.Top);
const float ImageSize = 32;
ws.Shapes.AddPicture(picPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
所以在这里我将我的图像插入第1行的第5个单元格,但是将其大小设置为32.但是,我可以访问此图像的高度和宽度。如何将第1行设置为该高度,将第5列设置为该宽度?
答案 0 :(得分:2)
如果将“列宽”的比率应用于“行高”,则下面会将单元格的高度和宽度设置为相应的图片高度和宽度:
var sh = ws.Shapes.AddPicture(picPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
oRange.Rows[1].RowHeight = sh.Height;
oRange.Columns[1].ColumnWidth = sh.Width;
这不是完美的答案,因为很难将Excel列宽设置为确切的数字。例如,默认的Excel列宽为8.43,下一个增量为8.57。为什么?;因为它是基于Normal字体的数量 可以放在单元格中的字符:https://support.microsoft.com/en-us/help/214123/description-of-how-column-widths-are-determined-in-excel
这里应用近似比率(不完美):
double rColRow = 6; // Ratio of units of measure: columns widths to row heights
double rImgColWidth = 5.9; // Ratio of units of measure: image size and column widths
oRange.Rows[1].RowHeight = (sh.Width * rColRow / rImgColWidth);
oRange.Columns[1].ColumnWidth = (sh.Height / rImgColWidth);