所以我放弃了
picture.To.Column = cell.Start.Column;
picture.To.Row = cell.Start.Row;
因为我无法让它工作并决定使用以下方法计算我自己的尺寸:
picture.SetSize(width, height);
诀窍是了解 Excel 实际如何计算宽度和高度。
单元格的高度:它以点为单位进行测量,但我们需要像素。一英寸有 72 个点。可以使用以下公式将点转换为像素:点* (1/72.0) * DPI。 DPI 是每英寸点数,可以使用以下方法找到:
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
float dpiY = graphics.DpiY;
}
因此,为了计算单元格的高度(以像素为单位),我使用了
private static int GetHeightInPixels(ExcelRange cell)
{
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
float dpiY = graphics.DpiY;
return (int)(cell.Worksheet.Row(cell.Start.Row).Height * (1 / 72.0) * dpiY);
}
}
单元格的宽度:这有点棘手。基本上,Excel 中单元格的宽度等于单元格可以水平包含的字符数(使用默认字体格式化)。
例如
该列的长度为 12,可以包含 12 个 Calibri(11) 字体的数字。
That is also my excel default since my body default is calibri(11)
这是一个article https://support.microsoft.com/en-us/help/214123/description-of-how-column-widths-are-determined-in-excel更深入地解释它。
下一个问题是如何将其转换为像素。
首先,我们需要了解默认字体中字符的长度是多少。可以在 System.Windows.Forms 命名空间中使用 TextRenderer.MeasureText。但是我正在使用 .Net Core 并且需要另一种方式。另一种方法是使用 System.Drawing.Common 核心库,该库现在处于预览状态。
public static float MeasureString(string s, Font font)
{
using (var g = Graphics.FromHwnd(IntPtr.Zero))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
return g.MeasureString(s, font, int.MaxValue, StringFormat.GenericTypographic).Width;
}
}
然后我使用该方法来计算像素宽度,如下所示
private static int GetWidthInPixels(ExcelRange cell)
{
double columnWidth = cell.Worksheet.Column(cell.Start.Column).Width;
Font font = new Font(cell.Style.Font.Name, cell.Style.Font.Size, FontStyle.Regular);
double pxBaseline = Math.Round(MeasureString("1234567890", font) / 10);
return (int)(columnWidth * pxBaseline);
}
编辑:请注意,当显示设置下缩放系数设置为超过 100% 时,仍然会发生重叠